HTML - это... Что такое HTML?
HTML (от англ. HyperText Markup Language — «язык разметки гипертекста») — стандартный язык разметки документов во Всемирной паутине. Большинство веб-страниц создаются при помощи языка HTML (или XHTML). Язык HTML интерпретируется браузерами и отображается в виде документа в удобной для человека форме.
HTML является приложением («частным случаем») SGML (стандартного обобщённого языка разметки) и соответствует международному стандарту ISO 8879. XHTML же является приложением XML.
Общее представление
Язык HTML был разработан британским учёным Тимом Бернерсом-Ли приблизительно в 1986—1991 годах в стенах Европейского Центра ядерных исследований в Женеве (Швейцария). HTML создавался как язык для обмена научной и технической документацией, пригодный для использования людьми, не являющимися специалистами в области вёрстки. HTML успешно справлялся с проблемой сложности SGML путём определения небольшого набора структурных и семантических элементов — дескрипторов. Дескрипторы также часто называют «тегами». С помощью HTML можно легко создать относительно простой, но красиво оформленный документ. Помимо упрощения структуры документа, в HTML внесена поддержка гипертекста. Мультимедийные возможности были добавлены позже.
Изначально язык HTML был задуман и создан как средство структурирования и форматирования документов без их привязки к средствам воспроизведения (отображения). В идеале, текст с разметкой HTML должен был без стилистических и структурных искажений воспроизводиться на оборудовании с различной технической оснащённостью (цветной экран современного компьютера, монохромный экран органайзера, ограниченный по размерам экран мобильного телефона или устройства и программы голосового воспроизведения текстов). Однако современное применение HTML очень далеко от его изначальной задачи. Например, тег <TABLE>, несколько раз использованный для форматирования страницы, которую вы на данный момент читаете, предназначен для создания в документах самых обычных таблиц, но, как можно убедиться, здесь нет ни одной таблицы. С течением времени основная идея платформонезависимости языка HTML была принесена в жертву современным потребностям в мультимедийном и графическом оформлении.
Браузеры
Текстовые документы, содержащие разметку на языке HTML (такие документы традиционно имеют расширение .html или .htm), обрабатываются специальными приложениями, которые отображают документ в его форматированном виде. Такие приложения, называемые «браузерами» или «интернет-обозревателями», обычно предоставляют пользователю удобный интерфейс для запроса веб-страниц, их просмотра (и вывода на иные внешние устройства) и, при необходимости, отправки введённых пользователем данных на сервер. Наиболее популярными на сегодняшний день браузерами являются Google Chrome, Mozilla Firefox, Opera, Internet Explorer и Safari (см.: Браузер#Рыночные доли).
Версии
Официальной спецификации HTML 1.0 не существует. До 1995 года существовало множество неофициальных стандартов HTML. Чтобы стандартная версия отличалась от них, ей сразу присвоили второй номер.
Версия 3 была предложена Консорциумом всемирной паутины (W3C) в марте 1995 года и обеспечивала много новых возможностей, таких как создание таблиц, «обтекание» изображений текстом и отображение сложных математических формул. Даже при том, что этот стандарт был совместим со второй версией, реализация его была сложна для браузеров того времени. Версия 3.1 официально никогда не предлагалась, и следующей версией стандарта HTML стала 3.2, в которой были опущены многие нововведения версии 3.0, но добавлены нестандартные элементы, поддерживаемые браузерами Netscape Navigator и Mosaic.
В версии HTML 4.0 произошла некоторая «очистка» стандарта. Многие элементы были отмечены как устаревшие и нерекомендованные (англ. deprecated). В частности, элемент font, используемый для изменения свойств шрифта, был помечен как устаревший (вместо него рекомендуется использовать таблицы стилей CSS).
В 1998 году консорциум Всемирной паутины начал работу над новым языком разметки, основанном на HTML 4, но соответствующим синтаксису XML. Впоследствии новый язык получил название XHTML. Первая версия XHTML 1.0 одобрена в качестве Рекомендации консорциума Всемирной паутины 26 января 2000 года.
Планируемая версия XHTML 2.0 должна была разорвать совместимость со старыми версиями HTML и XHTML, но 2 июля 2009 года консорциум Всемирной паутины объявил, что полномочия рабочей группы XHTML2 истекают в конце 2009 года. Таким образом, была приостановлена вся дальнейшая разработка стандарта XHTML 2.0[6].
Перспективы
| Информация в этой статье или некоторых её разделах устарела. Вы можете помочь проекту, обновив её и убрав после этого данный шаблон. |
В настоящее время Консорциум всемирной паутины разрабатывает HTML версии 5. Черновой вариант спецификации языка появился в Интернете 20 ноября 2007 года.
Сообществом WHATWG (англ. Web Hypertext Application Technology Working Group), начиная с 2004 года, разрабатывается спецификация Web Applications 1.0, часто неофициально называемая «HTML 5», которая расширяет HTML (впрочем, имея и совместимый с XHTML 1.0 XML-синтаксис) для лучшего представления семантики различных типичных страниц, например форумов, сайтов аукционов, поисковых систем, онлайн-магазинов и т. д., которые не очень удачно вписываются в модель XHTML 2.
Структура HTML-документа
HTML — теговый язык разметки документов. Любой документ на языке HTML представляет собой набор элементов, причём начало и конец каждого элемента обозначается специальными пометками — тегами. Элементы могут быть пустыми, то есть не содержащими никакого текста и других данных (например, тег перевода строки <br>). В этом случае обычно не указывается закрывающий тег. Кроме того, элементы могут иметь атрибуты, определяющие какие-либо их свойства (например, размер шрифта для элемента font). Атрибуты указываются в открывающем теге. Вот примеры фрагментов HTML-документа:
- <strong>Текст между двумя тегами — открывающим и закрывающим.</strong>
- <a href="http://www.example.com">Здесь элемент содержит атрибут href.</a>
- А вот пример пустого элемента: <br>
Регистр, в котором набрано имя элемента и имена атрибутов, в HTML значения не имеет (в отличие от XHTML). Элементы могут быть вложенными. Например, следующий код:
<b> Этот текст будет полужирным, <i>а этот - ещё и курсивным</i> </b>даст такой результат:
Этот текст будет полужирным, а этот — ещё и курсивнымКроме элементов, в HTML-документах есть и сущности (англ. entities) — «специальные символы». Сущности начинаются с символа амперсанда и имеют вид &имя; или &#NNNN;, где NNNN — код символа в Юникоде в десятичной системе счисления.
Например, © — знак авторского права (©). Как правило, сущности используются для представления символов, отсутствующих в кодировке документа, или же для представления «специальных» символов: & — амперсанда (&), < — символа «меньше» (<) и > — символа «больше» (>), которые некорректно записывать «обычным» образом, из-за их особого значения в HTML.
Подробнее по этой теме см.: Википедия:Специальные символы.
Каждый HTML-документ, отвечающий спецификации HTML какой-либо версии, должен начинаться со строки объявления версии HTML <!DOCTYPE…>, которая обычно выглядит примерно так:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">Если эта строка не указана, то добиться корректного отображения документа в браузере становится труднее.
Далее обозначается начало и конец документа тегами <html> и </html> соответственно. Внутри этих тегов должны находиться теги заголовка (<head></head>) и тела (<body></body>) документа.
Варианты DOCTYPE для HTML 4.01
- Строгий (Strict): не содержит элементов, помеченных как «устаревшие» или «не одобряемые» (deprecated).
- Переходный (Transitional): содержит устаревшие теги в целях совместимости и упрощения перехода со старых версий HTML.
- С фреймами (Frameset): аналогичен переходному, но содержит также теги для создания наборов фреймов.
Варианты DOCTYPE для HTML 5
В HTML 5 используется только один вариант DOCTYPE:
Браузерные войны
В середине 1990-х годов основные производители браузеров — компании Netscape и Microsoft — начали внедрять собственные наборы элементов в HTML-разметку. Создалась путаница из различных конструкций для работы во Всемирной паутине, доступных для просмотра то в одном, то в другом браузере. Особенно большие трудности были при создании кросс-браузерных программ на языке JavaScript. Веб-мастерам приходилось создавать несколько вариантов страниц или прибегать к другим ухищрениям. На какое-то время проблема потеряла актуальность по двум причинам:
- Из-за вытеснения браузером Internet Explorer всех остальных браузеров. Соответственно, проблема веб-мастеров становилась проблемой пользователей альтернативных браузеров.
- Благодаря усилиям производителей других браузеров, которые либо следовали стандартам W3C (как Mozilla и Opera), либо пытались создать максимальную совместимость с Internet Explorer.
На современном этапе можно констатировать рост популярности браузеров, следующих рекомендациям W3C (это Mozilla Firefox и другие браузеры на движке Gecko; Safari, Google Chrome и другие браузеры на движке WebKit; Opera с движком Presto). Доля Internet Explorer на данный момент составляет менее 50 %.[источник не указан 43 дня]
В современной практике существует возможность упростить разработку кросс-браузерных программ на языке JavaScript с помощью различных библиотек и фреймворков. Например, таких как jQuery, sIFR и др.
Примечания
См. также
Ссылки
Литература
- Э. Фримен, Э. Фримен Изучаем HTML, XHTML и CSS = Head First HTML with CSS & XHTML. — П.: «Питер», 2010. — 656 с. — ISBN 978-5-49807-113-8
- Эд Титтел, Джефф Ноубл. HTML, XHTML и CSS для чайников, 7-е издание = HTML, XHTML & CSS For Dummies, 7th Edition. — М.: «Диалектика», 2011. — 400 с. — ISBN 978-5-8459-1752-2
- Питер Лабберс, Брайан Олберс, Фрэнк Салим. HTML5 для профессионалов: мощные инструменты для разработки современных веб-приложений = Pro HTML5 Programming: Powerful APIs for Richer Internet Application Development. — М.: «Вильямс», 2011. — 272 с. — ISBN 978-5-8459-1715-7
- Стивен Шафер. HTML, XHTML и CSS. Библия пользователя, 5-е издание = HTML, XHTML, and CSS Bible, 5th Edition. — М.: «Диалектика», 2010. — 656 с. — ISBN 978-5-8459-1676-1
- Фримен Эрик, Фримен Элизабет. Изучаем HTML, XHTML и CSS = Head First HTML with CSS & XHTML. — 1-е изд. — М.: «Питер», 2010. — С. 656. — ISBN 978-5-49807-113-8
| Перечни: Перечень стандартов ИСО • Перечень романизаций ISO • Перечень стандартов IECКатегории: Категория:Стандарты ISO • Категория:Протоколы OSI | |
| 1 • 2 • 3 • 4 • 5 • 6 • 7 • 9 • 16 • 31 (-0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13) • 128 • 216 • 217 • 226 • 228 • 233 • 259 • 269 • 296 • 302 • 306 • 428 • 639 (-1, -2, -3, -5, -6) • 646 • 690 • 732 • 764 • 843 • 898 • 1000 • 1004 • 1007 • 1073-1 • 1413 • 1538 • 1745 • 2014 • 2015 • 2022 • 2108 • 2145 • 2146 • 2281 • 2709 • 2711 • 2788 • 3029 • 3103 • 3166 (-1, -2, -3) • 3297 • 3307 • 3602 • 3864 • 3901 • 3977 • 4031 • 4157 • 4217 • 5218 • 5775 • 5776 • 5964 • 6166 • 6344 • 6346 • 6425 • 6429 • 6438 • 6523 • 6709 • 7001 • 7002 • 7098 • 7185 • 7388 • 7498 • 7736 • 7810 • 7811 • 7812 • 7813 • 7816 • 8000 • 8217 • 8571 • 8583 • 8601 • 8632 • 8652 • 8691 • 8807 • 8820-5 • 8859 (-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16) • 8879 • 9000 • 9075 • 9126 • 9241 • 9362 • 9407 • 9506 • 9529 • 9564 • 9594 • 9660 • 9897 • 9945 • 9984 • 9985 • 9995 | |
| 10006 • 10118-3 • 10160 • 10161 • 10165 • 10179 • 10206 • 10303 • 10303-11 • 10303-21 • 10303-22 • 10303-238 • 10303-28 • 10383 • 10487 • 10585 • 10589 • 10646 • 10664 • 10746 • 10861 • 10957 • 10962 • 10967 • 11073 • 11170 • 11179 • 11404 • 11544 • 11783 • 11784 • 11785 • 11801 • 11898 • 11940 • 11941 • 11941 (TR) • 11992 • 12006 • 12164 • 12182:1998 • 12207:1995 • 12207:2008 • 12234-2 • 13211 (-1, -2) • 13216 • 13250 • 13399 • 13406-2 • 13407 • 13450 • 13485 • 13490 • 13567 • 13568 • 13584 • 13616 • 14000 • 14031 • 14396 • 14443 • 14496-10 • 14496-14 • 14644 (-1, -2, -3, -4, -5, -6, -7, -8, -9) • 14649 • 14651 • 14698 • 14698-2 • 14750 • 14882 • 14971 • 15022 • 15189 • 15288 • 15291 • 15292 • 15408 • 15444 • 15445 • 15438 • 15504 • 15511 • 15686 • 15693 • 15706 • 15706-2 • 15707 • 15897 • 15919 • 15924 • 15926 • 15926 WIP • 15930 • 16023 • 16262 • 16750 • 17024 • 17025 • 17369 • 17799 • 18000 • 18004 • 18014 • 18245 • 18629 • 18916 • 19005 • 19011 • 19092-1 • 19092-2 • 19114 • 19115 • 19439 • 19501:2005 • 19752 • 19757 • 19770 • 19775-1 • 19794-5 | |
| 20000 • 20022 • 21000 • 21047 • 21827:2002 • 22000 • 23008-2 • 23270 • 23360 • 24613 • 24707 • 25178 • 26000 • 26300 • 26324 • 27000 series • 27000 • 27001 • 27002 • 27003 • 27004 • 27005 • 27006 • 27007 • 27729 • 27799 • 29199-2 • 29500 • 31000 • 32000 • 38500 • 42010 • 50001 • 80000 | |
| См. также: Все статьи, начинающиеся с «ISO» | |
dic.academic.ru
HTML - Wikipedia
".htm" and ".html" redirect here. For other uses, see HTM.Hypertext Markup Language (HTML) is the standard markup language for creating web pages and web applications. With Cascading Style Sheets (CSS) and JavaScript, it forms a triad of cornerstone technologies for the World Wide Web.[3]Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects, such as interactive forms, may be embedded into the rendered page. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets. Tags such as <img /> and <input /> introduce content into the page directly. Others such as <p>...</p> surround and provide information about document text and may include other tags as sub-elements. Browsers do not display the HTML tags, but use them to interpret the content of the page.
HTML can embed programs written in a scripting language such as JavaScript which affect the behavior and content of web pages. Inclusion of CSS defines the look and layout of content. The World Wide Web Consortium (W3C), maintainer of both the HTML and the CSS standards, has encouraged the use of CSS over explicit presentational HTML since 1997.[4]
History
The historic logo made by the W3C
An example website written in HTML Development
In 1980, physicist Tim Berners-Lee, a contractor at CERN, proposed and prototyped ENQUIRE, a system for CERN researchers to use and share documents. In 1989, Berners-Lee wrote a memo proposing an Internet-based hypertext system.[5] Berners-Lee specified HTML and wrote the browser and server software in late 1990. That year, Berners-Lee and CERN data systems engineer Robert Cailliau collaborated on a joint request for funding, but the project was not formally adopted by CERN. In his personal notes[6] from 1990 he listed[7] "some of the many areas in which hypertext is used" and put an encyclopedia first.
The first publicly available description of HTML was a document called "HTML Tags", first mentioned on the Internet by Tim Berners-Lee in late 1991.[8][9] It describes 18 elements comprising the initial, relatively simple design of HTML. Except for the hyperlink tag, these were strongly influenced by SGMLguid, an in-house Standard Generalized Markup Language (SGML)-based documentation format at CERN. Eleven of these elements still exist in HTML 4.[10]
HTML is a markup language that web browsers use to interpret and compose text, images, and other material into visual or audible web pages. Default characteristics for every item of HTML markup are defined in the browser, and these characteristics can be altered or enhanced by the web page designer's additional use of CSS. Many of the text elements are found in the 1988 ISO technical report TR 9537 Techniques for using SGML, which in turn covers the features of early text formatting languages such as that used by the RUNOFF command developed in the early 1960s for the CTSS (Compatible Time-Sharing System) operating system: these formatting commands were derived from the commands used by typesetters to manually format documents. However, the SGML concept of generalized markup is based on elements (nested annotated ranges with attributes) rather than merely print effects, with also the separation of structure and markup; HTML has been progressively moved in this direction with CSS.
Berners-Lee considered HTML to be an application of SGML. It was formally defined as such by the Internet Engineering Task Force (IETF) with the mid-1993 publication of the first proposal for an HTML specification, the "Hypertext Markup Language (HTML)" Internet Draft by Berners-Lee and Dan Connolly, which included an SGML Document type definition to define the grammar.[11][12] The draft expired after six months, but was notable for its acknowledgment of the NCSA Mosaic browser's custom tag for embedding in-line images, reflecting the IETF's philosophy of basing standards on successful prototypes.[13] Similarly, Dave Raggett's competing Internet-Draft, "HTML+ (Hypertext Markup Format)", from late 1993, suggested standardizing already-implemented features like tables and fill-out forms.[14]
After the HTML and HTML+ drafts expired in early 1994, the IETF created an HTML Working Group, which in 1995 completed "HTML 2.0", the first HTML specification intended to be treated as a standard against which future implementations should be based.[15]
Further development under the auspices of the IETF was stalled by competing interests. Since 1996, the HTML specifications have been maintained, with input from commercial software vendors, by the World Wide Web Consortium (W3C).[16] However, in 2000, HTML also became an international standard (ISO/IEC 15445:2000). HTML 4.01 was published in late 1999, with further errata published through 2001. In 2004, development began on HTML5 in the Web Hypertext Application Technology Working Group (WHATWG), which became a joint deliverable with the W3C in 2008, and completed and standardized on 28 October 2014.[17]
HTML versions timeline
November 24, 1995 HTML 2.0 was published as IETF RFC 1866. Supplemental RFCs added capabilities: January 14, 1997 HTML 3.2[18] was published as a W3C Recommendation. It was the first version developed and standardized exclusively by the W3C, as the IETF had closed its HTML Working Group on September 12, 1996.[19] Initially code-named "Wilbur",[20] HTML 3.2 dropped math formulas entirely, reconciled overlap among various proprietary extensions and adopted most of Netscape's visual markup tags. Netscape's blink element and Microsoft's marquee element were omitted due to a mutual agreement between the two companies.[16] A markup for mathematical formulas similar to that in HTML was not standardized until 14 months later in MathML. December 18, 1997 HTML 4.0[21] was published as a W3C Recommendation. It offers three variations:- Strict, in which deprecated elements are forbidden
- Transitional, in which deprecated elements are allowed
- Frameset, in which mostly only frame related elements are allowed.
HTML draft version timeline
October 1991 HTML Tags,[8] an informal CERN document listing 18 HTML tags, was first mentioned in public. June 1992 First informal draft of the HTML DTD,[35] with seven[36][37][38] subsequent revisions (July 15, August 6, August 18, November 17, November 19, November 20, November 22) November 1992 HTML DTD 1.1 (the first with a version number, based on RCS revisions, which start with 1.1 rather than 1.0), an informal draft[38] June 1993 Hypertext Markup Language[39] was published by the IETF IIIR Working Group as an Internet Draft (a rough proposal for a standard). It was replaced by a second version[40] one month later, followed by six further drafts published by IETF itself[41] that finally led to HTML 2.0 in RFC 1866. November 1993 HTML+ was published by the IETF as an Internet Draft and was a competing proposal to the Hypertext Markup Language draft. It expired in May 1994. April 1995 (authored March 1995) HTML 3.0[42] was proposed as a standard to the IETF, but the proposal expired five months later (28 September 1995)[43] without further action. It included many of the capabilities that were in Raggett's HTML+ proposal, such as support for tables, text flow around figures and the display of complex mathematical formulas.[43] W3C began development of its own Arena browser as a test bed for HTML 3 and Cascading Style Sheets,[44][45][46] but HTML 3.0 did not succeed for several reasons. The draft was considered very large at 150 pages and the pace of browser development, as well as the number of interested parties, had outstripped the resources of the IETF.[16] Browser vendors, including Microsoft and Netscape at the time, chose to implement different subsets of HTML 3's draft features as well as to introduce their own extensions to it.[16] (see Browser wars). These included extensions to control stylistic aspects of documents, contrary to the "belief [of the academic engineering community] that such things as text color, background texture, font size and font face were definitely outside the scope of a language when their only intent was to specify how a document would be organized."[16] Dave Raggett, who has been a W3C Fellow for many years, has commented for example: "To a certain extent, Microsoft built its business on the Web by extending HTML features."[16] January 2008 HTML5 was published as a Working Draft by the W3C.[47] Although its syntax closely resembles that of SGML, HTML5 has abandoned any attempt to be an SGML application and has explicitly defined its own "html" serialization, in addition to an alternative XML-based XHTML5 serialization.[48] 2011 HTML5 – Last Call On 14 February 2011, the W3C extended the charter of its HTML Working Group with clear milestones for HTML5. In May 2011, the working group advanced HTML5 to "Last Call", an invitation to communities inside and outside W3C to confirm the technical soundness of the specification. The W3C developed a comprehensive test suite to achieve broad interoperability for the full specification by 2014, which was the target date for recommendation.[49] In January 2011, the WHATWG renamed its "HTML5" living standard to "HTML". The W3C nevertheless continues its project to release HTML5.[50] 2012 HTML5 – Candidate Recommendation In July 2012, WHATWG and W3C decided on a degree of separation. W3C will continue the HTML5 specification work, focusing on a single definitive standard, which is considered as a "snapshot" by WHATWG. The WHATWG organization will continue its work with HTML5 as a "Living Standard". The concept of a living standard is that it is never complete and is always being updated and improved. New features can be added but functionality will not be removed.[51] In December 2012, W3C designated HTML5 as a Candidate Recommendation.[52] The criterion for advancement to W3C Recommendation is "two 100% complete and fully interoperable implementations".[53] 2014 HTML5 – Proposed Recommendation and Recommendation In September 2014, W3C moved HTML5 to Proposed Recommendation.[54] On 28 October 2014, HTML5 was released as a stable W3C Recommendation,[55] meaning the specification process is complete.[56]XHTML versions
XHTML is a separate language that began as a reformulation of HTML 4.01 using XML 1.0. It is no longer being developed as a separate standard.
- XHTML 1.0 was published as a W3C Recommendation on January 26, 2000,[57] and was later revised and republished on August 1, 2002. It offers the same three variations as HTML 4.0 and 4.01, reformulated in XML, with minor restrictions.
- XHTML 1.1[58] was published as a W3C Recommendation on May 31, 2001. It is based on XHTML 1.0 Strict, but includes minor changes, can be customized, and is reformulated using modules in the W3C recommendation "Modularization of XHTML", which was published on April 10, 2001.[59]
- XHTML 2.0 was a working draft, work on it was abandoned in 2009 in favor of work on HTML5 and XHTML5.[60][61][62] XHTML 2.0 was incompatible with XHTML 1.x and, therefore, would be more accurately characterized as an XHTML-inspired new language than an update to XHTML 1.x.
- An XHTML syntax, known as "XHTML5.1", is being defined alongside HTML5 in the HTML5 draft.[63]
Markup
HTML markup consists of several key components, including those called tags (and their attributes), character-based data types, character references and entity references. HTML tags most commonly come in pairs like <h2> and </h2>, although some represent empty elements and so are unpaired, for example <img>. The first tag in such a pair is the start tag, and the second is the end tag (they are also called opening tags and closing tags).
Another important component is the HTML document type declaration, which triggers standards mode rendering.
The following is an example of the classic "Hello, World!" program, a common test employed for comparing programming languages, scripting languages and markup languages. This example is made using 9 source lines of code:
<!DOCTYPE html> <html> <head> <title>This is a title</title> </head> <body> <p>Hello world!</p> </body> </html>(The text between <html> and </html> describes the web page, and the text between <body> and </body> is the visible page content. The markup text "<title>This is a title</title>" defines the browser page title.)
The Document Type Declaration <!DOCTYPE html> is for HTML5. If a declaration is not included, various browsers will revert to "quirks mode" for rendering.[64]
Elements
HTML documents imply a structure of nested HTML elements. These are indicated in the document by HTML tags, enclosed in angle brackets thus: <p>[65]
In the simple, general case, the extent of an element is indicated by a pair of tags: a "start tag" <p> and "end tag" </p>. The text content of the element, if any, is placed between these tags.
Tags may also enclose further tag markup between the start and end, including a mixture of tags and text. This indicates further (nested) elements, as children of the parent element.
The start tag may also include attributes within the tag. These indicate other information, such as identifiers for sections within the document, identifiers used to bind style information to the presentation of the document, and for some tags such as the <img> used to embed images, the reference to the image resource.
Some elements, such as the line break <br>, do not permit any embedded content, either text or further tags. These require only a single empty tag (akin to a start tag) and do not use an end tag.
Many tags, particularly the closing end tag for the very commonly used paragraph element <p>, are optional. An HTML browser or other agent can infer the closure for the end of an element from the context and the structural rules defined by the HTML standard. These rules are complex and not widely understood by most HTML coders.
The general form of an HTML element is therefore: <tag attribute1="value1" attribute2="value2">''content''</tag>. Some HTML elements are defined as empty elements and take the form <tag attribute1="value1" attribute2="value2">. Empty elements may enclose no content, for instance, the <br> tag or the inline <img> tag. The name of an HTML element is the name used in the tags. Note that the end tag's name is preceded by a slash character, "/", and that in empty elements the end tag is neither required nor allowed. If attributes are not mentioned, default values are used in each case.
Element examples
Header of the HTML document: <head>...</head>. The title is included in the head, for example:
<head> <title>The Title</title> </head>Headings: HTML headings are defined with the <h2> to <h6> tags:
<h2>Heading level 1</h2> <h3>Heading level 2</h3> <h4>Heading level 3</h4> <h5>Heading level 4</h5> <h5>Heading level 5</h5> <h6>Heading level 6</h6>Paragraphs:
<p>Paragraph 1</p> <p>Paragraph 2</p>Line breaks:<br>. The difference between <br> and <p> is that "br" breaks a line without altering the semantic structure of the page, whereas "p" sections the page into paragraphs. Note also that "br" is an empty element in that, although it may have attributes, it can take no content and it may not have an end tag.
<p>This <br> is a paragraph <br> with <br> line breaks</p>This is a link in HTML. To create a link the <a> tag is used. The href= attribute holds the URL address of the link.
<a href="https://www.wikipedia.org/">A link to Wikipedia!</a>Inputs:
There are many possible ways a user can give input/s like:
1 <input type="text" /> <!-- This is for text input --> 2 <input type="file" /> <!-- This is for uploading files --> 3 <input type="checkbox" /> <!-- This is for checkboxes -->Comments:
<!-- This is a comment -->Comments can help in the understanding of the markup and do not display in the webpage.
There are several types of markup elements used in HTML:
Structural markup indicates the purpose of text For example, <h3>Golf</h3> establishes "Golf" as a second-level heading. Structural markup does not denote any specific rendering, but most web browsers have default styles for element formatting. Content may be further styled using Cascading Style Sheets (CSS).[66] Presentational markup indicates the appearance of the text, regardless of its purpose For example, <b>boldface</b> indicates that visual output devices should render "boldface" in bold text, but gives little indication what devices that are unable to do this (such as aural devices that read the text aloud) should do. In the case of both <b>bold</b> and <i>italic</i>, there are other elements that may have equivalent visual renderings but that are more semantic in nature, such as <strong>strong text</strong> and <em>emphasised text</em> respectively. It is easier to see how an aural user agent should interpret the latter two elements. However, they are not equivalent to their presentational counterparts: it would be undesirable for a screen-reader to emphasize the name of a book, for instance, but on a screen such a name would be italicized. Most presentational markup elements have become deprecated under the HTML 4.0 specification in favor of using CSS for styling. Hypertext markup makes parts of a document into links to other documents An anchor element creates a hyperlink in the document and its href attribute sets the link's target URL. For example, the HTML markup, <a href="http://www.google.com/">Wikipedia</a>, will render the word "Wikipedia" as a hyperlink. To render an image as a hyperlink, an "img" element is inserted as content into the "a" element. Like "br", "img" is an empty element with attributes but no content or closing tag. <a href="http://example.org"><img src="image.gif" alt="descriptive text" border="0"></a>.Attributes
Most of the attributes of an element are name-value pairs, separated by "=" and written within the start tag of an element after the element's name. The value may be enclosed in single or double quotes, although values consisting of certain characters can be left unquoted in HTML (but not XHTML) .[67][68] Leaving attribute values unquoted is considered unsafe.[69] In contrast with name-value pair attributes, there are some attributes that affect the element simply by their presence in the start tag of the element,[8] like the ismap attribute for the img element.[70]
There are several common attributes that may appear in many elements :
- The id attribute provides a document-wide unique identifier for an element. This is used to identify the element so that stylesheets can alter its presentational properties, and scripts may alter, animate or delete its contents or presentation. Appended to the URL of the page, it provides a globally unique identifier for the element, typically a sub-section of the page. For example, the ID "Attributes" in http://en.wikipedia.org/wiki/HTML#Attributes
- The class attribute provides a way of classifying similar elements. This can be used for semantic or presentation purposes. For example, an HTML document might semantically use the designation to indicate that all elements with this class value are subordinate to the main text of the document. In presentation, such elements might be gathered together and presented as footnotes on a page instead of appearing in the place where they occur in the HTML source. Class attributes are used semantically in microformats. Multiple class values may be specified; for example puts the element into both the "notation" and the "important" classes.
- An author may use the style attribute to assign presentational properties to a particular element. It is considered better practice to use an element's id or class attributes to select the element from within a stylesheet, though sometimes this can be too cumbersome for a simple, specific, or ad hoc styling.
- The title attribute is used to attach subtextual explanation to an element. In most browsers this attribute is displayed as a tooltip.
- The lang attribute identifies the natural language of the element's contents, which may be different from that of the rest of the document. For example, in an English-language document: <p>Oh well, <span lang="fr">c'est la vie</span>, as they say in France.</p>
The abbreviation element, abbr, can be used to demonstrate some of these attributes :
<abbr title="Hypertext Markup Language">HTML</abbr>This example displays as HTML; in most browsers, pointing the cursor at the abbreviation should display the title text "Hypertext Markup Language."
Most elements take the language-related attribute dir to specify text direction, such as with "rtl" for right-to-left text in, for example, Arabic, Persian or Hebrew.[71]
Character and entity references
As of version 4.0, HTML defines a set of 252 character entity references and a set of 1,114,050 numeric character references, both of which allow individual characters to be written via simple markup, rather than literally. A literal character and its markup counterpart are considered equivalent and are rendered identically.
The ability to "escape" characters in this way allows for the characters < and & (when written as < and &, respectively) to be interpreted as character data, rather than markup. For example, a literal < normally indicates the start of a tag, and & normally indicates the start of a character entity reference or numeric character reference; writing it as & or & or & allows & to be included in the content of an element or in the value of an attribute. The double-quote character ("), when not used to quote an attribute value, must also be escaped as " or " or " when it appears within the attribute value itself. Equivalently, the single-quote character ('), when not used to quote an attribute value, must also be escaped as ' or ' (or as ' in HTML5 or XHTML documents[72][73]) when it appears within the attribute value itself. If document authors overlook the need to escape such characters, some browsers can be very forgiving and try to use context to guess their intent. The result is still invalid markup, which makes the document less accessible to other browsers and to other user agents that may try to parse the document for search and indexing purposes for example.
Escaping also allows for characters that are not easily typed, or that are not available in the document's character encoding, to be represented within element and attribute content. For example, the acute-accented e (é), a character typically found only on Western European and South American keyboards, can be written in any HTML document as the entity reference é or as the numeric references é or é, using characters that are available on all keyboards and are supported in all character encodings. Unicode character encodings such as UTF-8 are compatible with all modern browsers and allow direct access to almost all the characters of the world's writing systems.[74]
Data types
HTML defines several data types for element content, such as script data and stylesheet data, and a plethora of types for attribute values, including IDs, names, URIs, numbers, units of length, languages, media descriptors, colors, character encodings, dates and times, and so on. All of these data types are specializations of character data.
Document type declaration
HTML documents are required to start with a Document Type Declaration (informally, a "doctype"). In browsers, the doctype helps to define the rendering mode—particularly whether to use quirks mode.
The original purpose of the doctype was to enable parsing and validation of HTML documents by SGML tools based on the Document Type Definition (DTD). The DTD to which the DOCTYPE refers contains a machine-readable grammar specifying the permitted and prohibited content for a document conforming to such a DTD. Browsers, on the other hand, do not implement HTML as an application of SGML and by consequence do not read the DTD.
HTML5 does not define a DTD; therefore, in HTML5 the doctype declaration is simpler and shorter:[75]
An example of an HTML 4 doctype
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">This declaration references the DTD for the "strict" version of HTML 4.01. SGML-based validators read the DTD in order to properly parse the document and to perform validation. In modern browsers, a valid doctype activates standards mode as opposed to quirks mode.
In addition, HTML 4.01 provides Transitional and Frameset DTDs, as explained below. Transitional type is the most inclusive, incorporating current tags as well as older or "deprecated" tags, with the Strict DTD excluding deprecated tags. Frameset has all tags necessary to make frames on a page along with the tags included in transitional type[citation needed].
Semantic HTML
Semantic HTML is a way of writing HTML that emphasizes the meaning of the encoded information over its presentation (look). HTML has included semantic markup from its inception,[76] but has also included presentational markup, such as <font>, <i> and <center> tags. There are also the semantically neutral span and div tags. Since the late 1990s when Cascading Style Sheets were beginning to work in most browsers, web authors have been encouraged to avoid the use of presentational HTML markup with a view to the separation of presentation and content.[77]
In a 2001 discussion of the Semantic Web, Tim Berners-Lee and others gave examples of ways in which intelligent software "agents" may one day automatically crawl the web and find, filter and correlate previously unrelated, published facts for the benefit of human users.[78] Such agents are not commonplace even now, but some of the ideas of Web 2.0, mashups and price comparison websites may be coming close. The main difference between these web application hybrids and Berners-Lee's semantic agents lies in the fact that the current aggregation and hybridization of information is usually designed in by web developers, who already know the web locations and the API semantics of the specific data they wish to mash, compare and combine.
An important type of web agent that does crawl and read web pages automatically, without prior knowledge of what it might find, is the web crawler or search-engine spider. These software agents are dependent on the semantic clarity of web pages they find as they use various techniques and algorithms to read and index millions of web pages a day and provide web users with search facilities without which the World Wide Web's usefulness would be greatly reduced.
In order for search-engine spiders to be able to rate the significance of pieces of text they find in HTML documents, and also for those creating mashups and other hybrids as well as for more automated agents as they are developed, the semantic structures that exist in HTML need to be widely and uniformly applied to bring out the meaning of published text.[79]
Presentational markup tags are deprecated in current HTML and XHTML recommendations and are illegal in HTML5[citation needed].
Good semantic HTML also improves the accessibility of web documents (see also Web Content Accessibility Guidelines). For example, when a screen reader or audio browser can correctly ascertain the structure of a document, it will not waste the visually impaired user's time by reading out repeated or irrelevant information when it has been marked up correctly.
Delivery
HTML documents can be delivered by the same means as any other computer file. However, they are most often delivered either by HTTP from a web server or by email.
HTTP
The World Wide Web is composed primarily of HTML documents transmitted from web servers to web browsers using the Hypertext Transfer Protocol (HTTP). However, HTTP is used to serve images, sound, and other content, in addition to HTML. To allow the web browser to know how to handle each document it receives, other information is transmitted along with the document. This meta data usually includes the MIME type (e.g. text/html or application/xhtml+xml) and the character encoding (see Character encoding in HTML).
In modern browsers, the MIME type that is sent with the HTML document may affect how the document is initially interpreted. A document sent with the XHTML MIME type is expected to be well-formed XML; syntax errors may cause the browser to fail to render it. The same document sent with the HTML MIME type might be displayed successfully, since some browsers are more lenient with HTML.
The W3C recommendations state that XHTML 1.0 documents that follow guidelines set forth in the recommendation's Appendix C may be labeled with either MIME Type.[80] XHTML 1.1 also states that XHTML 1.1 documents should[81] be labeled with either MIME type.[82]
HTML e-mail
Most graphical email clients allow the use of a subset of HTML (often ill-defined) to provide formatting and semantic markup not available with plain text. This may include typographic information like coloured headings, emphasized and quoted text, inline images and diagrams. Many such clients include both a GUI editor for composing HTML e-mail messages and a rendering engine for displaying them. Use of HTML in e-mail is criticized by some because of compatibility issues, because it can help disguise phishing attacks, because of accessibility issues for blind or visually impaired people, because it can confuse spam filters and because the message size is larger than plain text.
Naming conventions
The most common filename extension for files containing HTML is .html. A common abbreviation of this is .htm, which originated because some early operating systems and file systems, such as DOS and the limitations imposed by FAT data structure, limited file extensions to three letters.[83]
HTML Application
An HTML Application (HTA; file extension ".hta") is a Microsoft Windows application that uses HTML and Dynamic HTML in a browser to provide the application's graphical interface. A regular HTML file is confined to the security model of the web browser's security, communicating only to web servers and manipulating only webpage objects and site cookies. An HTA runs as a fully trusted application and therefore has more privileges, like creation/editing/removal of files and Windows Registry entries. Because they operate outside the browser's security model, HTAs cannot be executed via HTTP, but must be downloaded (just like an EXE file) and executed from local file system.
HTML4 variations
Since its inception, HTML and its associated protocols gained acceptance relatively quickly.[by whom?] However, no clear standards existed in the early years of the language. Though its creators originally conceived of HTML as a semantic language devoid of presentation details,[84] practical uses pushed many presentational elements and attributes into the language, driven largely by the various browser vendors. The latest standards surrounding HTML reflect efforts to overcome the sometimes chaotic development of the language[85] and to create a rational foundation for building both meaningful and well-presented documents. To return HTML to its role as a semantic language, the W3C has developed style languages such as CSS and XSL to shoulder the burden of presentation. In conjunction, the HTML specification has slowly reined in the presentational elements.
There are two axes differentiating various variations of HTML as currently specified: SGML-based HTML versus XML-based HTML (referred to as XHTML) on one axis, and strict versus transitional (loose) versus frameset on the other axis.
SGML-based versus XML-based HTML
One difference in the latest HTML specifications lies in the distinction between the SGML-based specification and the XML-based specification. The XML-based specification is usually called XHTML to distinguish it clearly from the more traditional definition. However, the root element name continues to be "html" even in the XHTML-specified HTML. The W3C intended XHTML 1.0 to be identical to HTML 4.01 except where limitations of XML over the more complex SGML require workarounds. Because XHTML and HTML are closely related, they are sometimes documented in parallel. In such circumstances, some authors conflate the two names as (X)HTML or X(HTML).
Like HTML 4.01, XHTML 1.0 has three sub-specifications: strict, transitional and frameset.
Aside from the different opening declarations for a document, the differences between an HTML 4.01 and XHTML 1.0 document—in each of the corresponding DTDs—are largely syntactic. The underlying syntax of HTML allows many shortcuts that XHTML does not, such as elements with optional opening or closing tags, and even empty elements which must not have an end tag. By contrast, XHTML requires all elements to have an opening tag and a closing tag. XHTML, however, also introduces a new shortcut: an XHTML tag may be opened and closed within the same tag, by including a slash before the end of the tag like this: <br/>. The introduction of this shorthand, which is not used in the SGML declaration for HTML 4.01, may confuse earlier software unfamiliar with this new convention. A fix for this is to include a space before closing the tag, as such: <br />.[86]
To understand the subtle differences between HTML and XHTML, consider the transformation of a valid and well-formed XHTML 1.0 document that adheres to Appendix C (see below) into a valid HTML 4.01 document. To make this translation requires the following steps:
- The language for an element should be specified with a lang attribute rather than the XHTML xml:lang attribute. XHTML uses XML's built in language-defining functionality attribute.
- Remove the XML namespace (xmlns=URI). HTML has no facilities for namespaces.
- Change the document type declaration from XHTML 1.0 to HTML 4.01. (see DTD section for further explanation).
- If present, remove the XML declaration. (Typically this is: <?xml version="1.0" encoding="utf-8"?>).
- Ensure that the document's MIME type is set to text/html. For both HTML and XHTML, this comes from the HTTP Content-Type header sent by the server.
- Change the XML empty-element syntax to an HTML style empty element (<br /> to <br>).
Those are the main changes necessary to translate a document from XHTML 1.0 to HTML 4.01. To translate from HTML to XHTML would also require the addition of any omitted opening or closing tags. Whether coding in HTML or XHTML it may just be best to always include the optional tags within an HTML document rather than remembering which tags can be omitted.
A well-formed XHTML document adheres to all the syntax requirements of XML. A valid document adheres to the content specification for XHTML, which describes the document structure.
The W3C recommends several conventions to ensure an easy migration between HTML and XHTML (see HTML Compatibility Guidelines). The following steps can be applied to XHTML 1.0 documents only:
- Include both xml:lang and lang attributes on any elements assigning language.
- Use the empty-element syntax only for elements specified as empty in HTML.
- Include an extra space in empty-element tags: for example <br /> instead of <br>.
- Include explicit close tags for elements that permit content but are left empty (for example, <div></div>, not <div />).
- Omit the XML declaration.
By carefully following the W3C's compatibility guidelines, a user agent should be able to interpret the document equally as HTML or XHTML. For documents that are XHTML 1.0 and have been made compatible in this way, the W3C permits them to be served either as HTML (with a text/html MIME type), or as XHTML (with an application/xhtml+xml or application/xml MIME type). When delivered as XHTML, browsers should use an XML parser, which adheres strictly to the XML specifications for parsing the document's contents.
Transitional versus strict
HTML 4 defined three different versions of the language: Strict, Transitional (once called Loose) and Frameset. The Strict version is intended for new documents and is considered best practice, while the Transitional and Frameset versions were developed to make it easier to transition documents that conformed to older HTML specification or didn't conform to any specification to a version of HTML 4. The Transitional and Frameset versions allow for presentational markup, which is omitted in the Strict version. Instead, cascading style sheets are encouraged to improve the presentation of HTML documents. Because XHTML 1 only defines an XML syntax for the language defined by HTML 4, the same differences apply to XHTML 1 as well.
The Transitional version allows the following parts of the vocabulary, which are not included in the Strict version:
- A looser content model
- Inline elements and plain text are allowed directly in: body, blockquote, form, noscript and noframes
- Presentation related elements
- underline (u)(Deprecated. can confuse a visitor with a hyperlink.)
- strike-through (s)
- center (Deprecated. use CSS instead.)
- font (Deprecated. use CSS instead.)
- basefont (Deprecated. use CSS instead.)
- Presentation related attributes
- background (Deprecated. use CSS instead.) and bgcolor (Deprecated. use CSS instead.) attributes for body (required element according to the W3C.) element.
- align (Deprecated. use CSS instead.) attribute on div, form, paragraph (p) and heading (h2...h6) elements
- align (Deprecated. use CSS instead.), noshade (Deprecated. use CSS instead.), size (Deprecated. use CSS instead.) and width (Deprecated. use CSS instead.) attributes on hr element
- align (Deprecated. use CSS instead.), border, vspace and hspace attributes on img and object (caution: the object element is only supported in Internet Explorer (from the major browsers)) elements
- align (Deprecated. use CSS instead.) attribute on legend and caption elements
- align (Deprecated. use CSS instead.) and bgcolor (Deprecated. use CSS instead.) on table element
- nowrap (Obsolete), bgcolor (Deprecated. use CSS instead.), width, height on td and th elements
- bgcolor (Deprecated. use CSS instead.) attribute on tr element
- clear (Obsolete) attribute on br element
- compact attribute on dl, dir and menu elements
- type (Deprecated. use CSS instead.), compact (Deprecated. use CSS instead.) and start (Deprecated. use CSS instead.) attributes on ol and ul elements
- type and value attributes on li element
- width attribute on pre element
- Additional elements in Transitional specification
- menu (Deprecated. use CSS instead.) list (no substitute, though unordered list is recommended)
- dir (Deprecated. use CSS instead.) list (no substitute, though unordered list is recommended)
- isindex (Deprecated.) (element requires server-side support and is typically added to documents server-side, form and input elements can be used as a substitute)
- applet (Deprecated. use the object element instead.)
- The language (Obsolete) attribute on script element (redundant with the type attribute).
- Frame related entities
- iframe
- noframes
- target (Deprecated in the map, link and form elements.) attribute on a, client-side image-map (map), link, form and base elements
The Frameset version includes everything in the Transitional version, as well as the frameset element (used instead of body) and the frame element.
Frameset versus transitional
In addition to the above transitional differences, the frameset specifications (whether XHTML 1.0 or HTML 4.01) specify a different content model, with frameset replacing body, that contains either frame elements, or optionally noframes with a body.
Summary of specification versions
As this list demonstrates, the loose versions of the specification are maintained for legacy support. However, contrary to popular misconceptions, the move to XHTML does not imply a removal of this legacy support. Rather the X in XML stands for extensible and the W3C is modularizing the entire specification and opening it up to independent extensions. The primary achievement in the move from XHTML 1.0 to XHTML 1.1 is the modularization of the entire specification. The strict version of HTML is deployed in XHTML 1.1 through a set of modular extensions to the base XHTML 1.1 specification. Likewise, someone looking for the loose (transitional) or frameset specifications will find similar extended XHTML 1.1 support (much of it is contained in the legacy or frame modules). The modularization also allows for separate features to develop on their own timetable. So for example, XHTML 1.1 will allow quicker migration to emerging XML standards such as MathML (a presentational and semantic math language based on XML) and XForms—a new highly advanced web-form technology to replace the existing HTML forms.
In summary, the HTML 4 specification primarily reined in all the various HTML implementations into a single clearly written specification based on SGML. XHTML 1.0, ported this specification, as is, to the new XML defined specification. Next, XHTML 1.1 takes advantage of the extensible nature of XML and modularizes the whole specification. XHTML 2.0 was intended to be the first step in adding new features to the specification in a standards-body-based approach.
HTML5 variations
WHATWG HTML versus HTML5
The WHATWG considers their work as living standard HTML for what constitutes the state of the art in major browser implementations by Apple (Safari), Microsoft (Edge), Google (Chrome), Mozilla (Firefox), Opera (Opera), and others. HTML5 is specified by the HTML Working Group of the W3C following the W3C process. As of 2013[update] both specifications are similar and mostly derived from each other, i.e., the work on HTML5 started with an older WHATWG draft, and later the WHATWG living standard was based on HTML5 drafts in 2011.[87][88]
Hypertext features not in HTML
HTML lacks some of the features found in earlier hypertext systems, such as source tracking, fat links and others.[89] Even some hypertext features that were in early versions of HTML have been ignored by most popular web browsers until recently[when?], such as the link element and in-browser Web page editing.
Sometimes Web services or browser manufacturers remedy these shortcomings. For instance, wikis and content management systems allow surfers to edit the Web pages they visit.
WYSIWYG editors
There are some WYSIWYG editors (What You See Is What You Get), in which the user lays out everything as it is to appear in the HTML document using a graphical user interface (GUI), often similar to word processors. The editor renders the document rather than show the code, so authors do not require extensive knowledge of HTML.
The WYSIWYG editing model has been criticized,[90][91] primarily because of the low quality of the generated code; there are voices advocating a change to the WYSIWYM model (What You See Is What You Mean).
WYSIWYG editors remain a controversial topic because of their perceived flaws such as:
- Relying mainly on layout as opposed to meaning, often using markup that does not convey the intended meaning but simply copies the layout.[92]
- Often producing extremely verbose and redundant code that fails to make use of the cascading nature of HTML and CSS.
- Often producing ungrammatical markup, called tag soup or semantically incorrect markup (such as <em> for italics).
- As a great deal of the information in HTML documents is not in the layout, the model has been criticized for its "what you see is all you get"-nature.[93]
See also
References
- ^ "HTML 5.1 2nd Edition". W3C. 2017-10-03. Retrieved 2017-10-03.
- ^ "HTML 5.2 Editor's Draft". W3C. 2017-10-13. Retrieved 2017-10-17.
- ^ Flanagan, David. JavaScript - The definitive guide (6 ed.). p. 1. JavaScript is part of the triad of technologies that all Web developers must learn: HTML to specify the content of web pages, CSS to specify the presentation of web pages, and JavaScript to specify the behaviour of web pages.
- ^ "HTML 4.0 Specification — W3C Recommendation — Conformance: requirements and recommendations". World Wide Web Consortium. December 18, 1997. Retrieved July 6, 2015.
- ^ Tim Berners-Lee, "Information Management: A Proposal." CERN (March 1989, May 1990). W3.org
- ^ Tim Berners-Lee, "Design Issues"
- ^ Tim Berners-Lee, "Design Issues"
- ^ a b c "Tags used in HTML". World Wide Web Consortium. November 3, 1992. Retrieved November 16, 2008.
- ^ "First mention of HTML Tags on the www-talk mailing list". World Wide Web Consortium. October 29, 1991. Retrieved April 8, 2007.
- ^ "Index of elements in HTML 4". World Wide Web Consortium. December 24, 1999. Retrieved April 8, 2007.
- ^ Tim Berners-Lee (December 9, 1991). "Re: SGML/HTML docs, X Browser (archived www-talk mailing list post)". Retrieved June 16, 2007. SGML is very general. HTML is a specific application of the SGML basic syntax applied to hypertext documents with simple structure.
- ^ Berners-Lee, Tim; Connolly, Daniel (June 1993). "Hypertext Markup Language (HTML): A Representation of Textual Information and MetaInformation for Retrieval and Interchange". w3.org. Retrieved 2017-01-04.
- ^ Raymond, Eric. "IETF and the RFC Standards Process". The Art of Unix Programming. Archived from the original on 2005-03-17. In IETF tradition, standards have to arise from experience with a working prototype implementation — but once they become standards, code that does not conform to them is considered broken and mercilessly scrapped. ...Internet-Drafts are not specifications; software implementers and vendors are specifically barred from claiming compliance with them as if they were specifications. Internet-Drafts are focal points for discussion, usually in a working group... Once an Internet-Draft has been published with an RFC number, it is a specification to which implementers may claim conformance. It is expected that the authors of the RFC and the community at large will begin correcting the specification with field experience.
- ^ Raggett, Dave. "A Review of the HTML+ Document Format". Archived from the original on 2000-02-29. The hypertext markup language HTML was developed as a simple non-proprietary delivery format for global hypertext. HTML+ is a set of modular extensions to HTML and has been developed in response to a growing understanding of the needs of information providers. These extensions include text flow around floating figures, fill-out forms, tables and mathematical equations.
- ^ Berners-Lee, Tim; Connelly, Daniel (November 1995). "RFC 1866 – Hypertext Markup Language – 2.0". Internet Engineering Task Force. Retrieved 1 December 2010. This document thus defines an HTML 2.0 (to distinguish it from the previous informal specifications). Future (generally upwardly compatible) versions of HTML with new features will be released with higher version numbers.
- ^ a b c d e f Raggett, Dave (1998). Raggett on HTML 4. Retrieved July 9, 2007.
- ^ "HTML5 – Hypertext Markup Language – 5.0". Internet Engineering Task Force. 28 October 2014. Retrieved 25 November 2014. This document recommends HTML 5.0 after completion.
- ^ "HTML 3.2 Reference Specification". World Wide Web Consortium. January 14, 1997. Retrieved November 16, 2008.
- ^ "IETF HTML WG". Retrieved June 16, 2007. Note: This working group is closed
- ^ a b Arnoud Engelfriet. "Introduction to Wilbur". Web Design Group. Retrieved June 16, 2007.
- ^ "HTML 4.0 Specification". World Wide Web Consortium. December 18, 1997. Retrieved November 16, 2008.
- ^ "HTML 4 – 4 Conformance: requirements and recommendations". Retrieved December 30, 2009.
- ^ "HTML 4.0 Specification". World Wide Web Consortium. April 24, 1998. Retrieved November 16, 2008.
- ^ "HTML 4.01 Specification". World Wide Web Consortium. December 24, 1999. Retrieved November 16, 2008.
- ^ a b ISO (2000). "ISO/IEC 15445:2000 – Information technology – Document description and processing languages – HyperText Markup Language (HTML)". Retrieved December 26, 2009.
- ^ Cs.Tcd.Ie. Cs.Tcd.Ie (2000-05-15). Retrieved on 2012-02-16.
- ^ "HTML5: A vocabulary and associated APIs for HTML and XHTML". World Wide Web Consortium. 28 October 2014. Retrieved 31 October 2014.
- ^ "Open Web Platform Milestone Achieved with HTML5 Recommendation" (Press release). World Wide Web Consortium. 28 October 2014. Retrieved 31 October 2014.
- ^ "HTML 5.1". World Wide Web Consortium. 1 November 2016. Retrieved 6 January 2017.
- ^ "HTML 5.1 is a W3C Recommendation". World Wide Web Consortium. 1 November 2016. Retrieved 6 January 2017.
- ^ Philippe le Hegaret (17 November 2016). "HTML 5.1 is the gold standard". World Wide Web Consortium. Retrieved 6 January 2017.
- ^ "HTML 5.2". World Wide Web Consortium. 14 December 2017. Retrieved 15 December 2017.
- ^ "HTML 5.2 is now a W3C Recommendation". World Wide Web Consortium. 14 December 2017. Retrieved 15 December 2017.
- ^ Charles McCathie Nevile (14 December 2017). "HTML 5.2 is done, HTML 5.3 is coming". World Wide Web Consortium. Retrieved 15 December 2017.
- ^ Connolly, Daniel (6 June 1992). "MIME as a hypertext architecture". CERN. Retrieved 24 October 2010.
- ^ Connolly, Daniel (15 July 1992). "HTML DTD enclosed". CERN. Retrieved 24 October 2010.
- ^ Connolly, Daniel (18 August 1992). "document type declaration subset for Hyper Text Markup Language as defined by the World Wide Web project". CERN. Retrieved 24 October 2010.
- ^ a b Connolly, Daniel (24 November 1992). "Document Type Definition for the Hyper Text Markup Language as used by the World Wide Web application". CERN. Retrieved 24 October 2010. See section "Revision History"
- ^ Berners-Lee, Tim; Connolly, Daniel (June 1993). "Hyper Text Markup Language (HTML) Internet Draft version 1.1". IETF IIIR Working Group. Retrieved 18 September 2010.
- ^ Berners-Lee, Tim; Connolly, Daniel (June 1993). "Hypertext Markup Language (HTML) Internet Draft version 1.2". IETF IIIR Working Group. Retrieved 18 September 2010.
- ^ Berners-Lee, Tim; Connolly, Daniel (28 November 1994). "HyperText Markup Language Specification – 2.0 INTERNET DRAFT". IETF. Retrieved 24 October 2010.
- ^ "HTML 3.0 Draft (Expired!) Materials". World Wide Web Consortium. December 21, 1995. Retrieved November 16, 2008.
- ^ a b "HyperText Markup Language Specification Version 3.0". Retrieved June 16, 2007.
- ^ Raggett, Dave (28 March 1995). "HyperText Markup Language Specification Version 3.0". HTML 3.0 Internet Draft Expires in six months. World Wide Web Consortium. Retrieved 17 June 2010.
- ^ Bowers, Neil. "Weblint: Just Another Perl Hack".
- ^ Lie, Håkon Wium; Bos, Bert (April 1997). Cascading style sheets: designing for the Web. Addison Wesley Longman. p. 263. Retrieved 9 June 2010.
- ^ "HTML5". World Wide Web Consortium. June 10, 2008. Retrieved November 16, 2008.
- ^ "HTML5, one vocabulary, two serializations". Retrieved February 25, 2009.
- ^ "W3C Confirms May 2011 for HTML5 Last Call, Targets 2014 for HTML5 Standard". World Wide Web Consortium. 14 February 2011. Retrieved 18 February 2011.
- ^ Hickson, Ian. "HTML Is the New HTML5". Retrieved 21 January 2011.
- ^ "HTML5 gets the splits". netmagazine.com. Retrieved 23 July 2012.
- ^ "HTML5". W3.org. 2012-12-17. Retrieved 2013-06-15.
- ^ "When Will HTML5 Be Finished?". FAQ. WHAT Working Group. Retrieved 29 November 2009.
- ^ "Call for Review: HTML5 Proposed Recommendation Published W3C News". W3.org. 2014-09-16. Retrieved 2014-09-27.
- ^ "Open Web Platform Milestone Achieved with HTML5 Recommendation". W3C. 28 October 2014. Retrieved 29 October 2014.
- ^ "HTML5 specification finalized, squabbling over specs continues". Ars Technica. 2014-10-29. Retrieved 2014-10-29.
- ^ "XHTML 1.0: The Extensible HyperText Markup Language (Second Edition)". World Wide Web Consortium. January 26, 2000. Retrieved November 16, 2008.
- ^ "XHTML 1.1 – Module-based XHTML — Second Edition". World Wide Web Consortium. February 16, 2007. Retrieved November 16, 2008.
- ^ "Modularization of XHTML". www.w3.org. Retrieved 2017-01-04.
- ^ "XHTM 2.0". World Wide Web Consortium. July 26, 2006. Retrieved November 16, 2008.
- ^ "XHTML 2 Working Group Expected to Stop Work End of 2009, W3C to Increase Resources on HTML5". World Wide Web Consortium. July 17, 2009. Retrieved November 16, 2008.
- ^ "W3C XHTML FAQ".
- ^ "HTML5". W3C. 19 October 2013.
- ^ Activating Browser Modes with Doctype. Hsivonen.iki.fi. Retrieved on 2012-02-16.
- ^ "HTML Elements". w3schools. Retrieved 16 March 2015.
- ^ "CSS Introduction". W3schools. Retrieved 16 March 2015.
- ^ "On SGML and HTML". World Wide Web Consortium. Retrieved November 16, 2008.
- ^ "XHTML 1.0 – Differences with HTML 4". World Wide Web Consortium. Retrieved November 16, 2008.
- ^ Korpela, Jukka (July 6, 1998). "Why attribute values should always be quoted in HTML". Cs.tut.fi. Retrieved November 16, 2008.
- ^ "Objects, Images, and Applets in HTML documents". World Wide Web Consortium. December 24, 1999. Retrieved November 16, 2008.
- ^ "H56: Using the dir attribute on an inline element to resolve problems with nested directional runs". Techniques for WCAG 2.0. W3C. Retrieved 18 September 2010.
- ^ "Character Entity Reference Chart". World Wide Web Consortium. October 24, 2012.
- ^ "The Named Character Reference '". World Wide Web Consortium. January 26, 2000.
- ^ "The Unicode Standard: A Technical Introduction". Retrieved 2010-03-16.
- ^ "HTML: The Markup Language (an HTML language reference)". Retrieved 2013-08-19.
- ^ Berners-Lee, Tim; Fischetti, Mark (2000). Weaving the Web: The Original Design and Ultimate Destiny of the World Wide Web by Its Inventor. San Francisco: Harper. ISBN 978-0-06-251587-2.
- ^ Raggett, Dave (2002). "Adding a touch of style". W3C. Retrieved October 2, 2009. This article notes that presentational HTML markup may be useful when targeting browsers "before Netscape 4.0 and Internet Explorer 4.0". See the list of web browsers to confirm that these were both released in 1997.
- ^ Tim Berners-Lee, James Hendler and Ora Lassila (2001). "The Semantic Web". Scientific American. Retrieved October 2, 2009.
- ^ Nigel Shadbolt, Wendy Hall and Tim Berners-Lee (2006). "The Semantic Web Revisited" (PDF). IEEE Intelligent Systems. Retrieved October 2, 2009.
- ^ "XHTML 1.0 The Extensible HyperText Markup Language (Second Edition)". World Wide Web Consortium. 2002 [2000]. Retrieved December 7, 2008. XHTML Documents which follow the guidelines set forth in Appendix C, "HTML Compatibility Guidelines" may be labeled with the Internet Media Type "text/html" [RFC2854], as they are compatible with most HTML browsers. Those documents, and any other document conforming to this specification, may also be labeled with the Internet Media Type "application/xhtml+xml" as defined in [RFC3236].
- ^ "RFC 2119: Key words for use in RFCs to Indicate Requirement Levels". Harvard University. 1997. Retrieved December 7, 2008. 3. SHOULD This word, or the adjective "RECOMMENDED", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.
- ^ "XHTML 1.1 – Module-based XHTML — Second Edition". World Wide Web Consortium. 2007. Retrieved December 7, 2008. XHTML 1.1 documents SHOULD be labeled with the Internet Media Type text/html as defined in [RFC2854] or application/xhtml+xml as defined in [RFC3236].
- ^ "Naming Files, Paths, and Namespaces". Microsoft. Retrieved 16 March 2015.
- ^ HTML Design Constraints, W3C Archives
- ^ WWW:BTB – HTML, Pris Sears
- ^ Freeman, E (2005). Head First HTML. O'Reilly.
- ^ Hickson, Ian (2011-01-19). "HTML is the new HTML5". The WHATWG blog. Retrieved 2013-01-14.
- ^ "HTML5 — Smile, it's a Snapshot!". W3C Blog. 2012-12-17. Retrieved 2013-01-14.
- ^ Jakob Nielsen (January 3, 2005). "Reviving Advanced Hypertext". Retrieved June 16, 2007.
- ^ Sauer, C.: WYSIWIKI – Questioning WYSIWYG in the Internet Age. In: Wikimania (2006)
- ^ Spiesser, J., Kitchen, L.: Optimization of HTML automatically generated by WYSIWYG programs. In: 13th International Conference on World Wide Web, pp. 355—364. WWW '04. ACM, New York, NY (New York, NY, U.S., May 17–20, 2004)
- ^ XHTML Reference: blockquote. Xhtml.com. Retrieved on 2012-02-16.
- ^ Doug Engelbart's INVISIBLE REVOLUTION . Invisiblerevolution.net. Retrieved on 2012-02-16.
External links
en.wikipedia.org
HTML — Структура html-документа и теги для его создания / ProgLang
HTML — расшифровывается как «язык гипертекстовой разметки» (англ. HyperText Markup Language), который является наиболее широко используемым языком для написания веб-страниц.
- Гипертекст относится к способу связывания веб-страниц (HTML-документов). Таким образом, ссылка, доступная на веб-странице, называется гипертекстом.
- Как следует из названия, HTML — это язык разметки, что означает, что Вы используете HTML, чтобы просто «разметить» текстовый документ с тегами, которые сообщают веб-браузеру, как структурировать его для отображения.
Первоначально HTML был разработан с целью определения структуры документов, таких как заголовки, списки, абзацы и так далее, чтобы облегчить обмен научной информацией между исследователями.
Теперь HTML широко используется для форматирования веб-страниц с помощью различных тегов, доступных на языке HTML.
HTML-документ
В следующем примере показан HTML-документ в простейшей форме:
<!DOCTYPE html> <html> <head> <title>Заголовок документа</title> </head> <body> <h2>Заголовок</h2> <p>Здесь содержание документа...</p> </body> </html>Давайте сохраним код в HTML-файле document.html с помощью вашего любимого текстового редактора. И откройте файл с помощью веб-браузера, такого как Internet Explorer, Google Chrome или Firefox и др. Он должен показать следующий результат:
Теги для создания HTML-документа
Как уже говорилось ранее, HTML является языком разметки и использует различные теги для форматирования содержимого. Эти теги заключены в угловые скобки . Большинство тегов имеют соответствующие закрывающие теги, за исключением нескольких тегов. Например, тег <html> имеет закрывающий тег </html> и тег <body> имеет тег закрытия </body> и другие.
В приведенном выше примере используются следующие теги для создания HTML-документа:
| Тег | Описание |
| <!DOCTYPE...> | Этот тег определяет тип документа и версию HTML. |
| <html> | Этот тег охватывает полный HTML-документ и в основном состоит из заголовка документа, который представлен тегами <head>...</head> и телом документа, которое представлено тегами <body>...</body>. |
| <head> | Этот тег представляет заголовок документа, который может содержать другие html-теги, такие как <title>, <link> и т.д. |
| <title> | Тег <title> используется внутри тега <head>, чтобы указать название документа. |
| <body> | Этот тег представляет тело документа, в котором хранятся другие html-теги, такие как <h2>, <div>, <p> и другие. |
| <h2> | Этот тег представляет заголовок. |
| <p> | Этот тег представляет абзац. |
Знание этих тегов вполне хватит чтобы создать html-документ (html-страницу).
Чтобы изучить HTML, Вам нужно знать различные теги и понимать, как они ведут себя при форматировании текстового документа. Учить HTML легко, так как пользователям нужно только выучить использование разных тегов, чтобы отформатировать текст или изображения, тем самым сделать красивую веб-страницу.
Консорциум World Wide Web (W3C) рекомендует использовать строчные теги, начиная с HTML 4.
Структура HTML-документа
Структура типичного HTML-документа будет иметь следующий вид:
Тег декларации документа <html> <head> <title>Теги, связанные с заголовком документа</title> </head> <body> Теги, связанные с телом документа </body> </html>Мы изучим все теги заголовка и тела в последующих уроках, теперь давайте посмотрим, что такое тег декларации документа.
Декларация <!DOCTYPE>
Тег декларация <!DOCTYPE> используется веб-браузером для понимания версии HTML, используемой в документе. Текущая версия HTML — 5, и она использует следующее объявление:
<!DOCTYPE html>Существует много других типов объявлений, которые могут использоваться в документе HTML в зависимости от того, какая версия HTML используется. Мы увидим более подробную информацию об этом при обсуждении тега <!DOCTYPE...> вместе с другими тегами HTML.
Поделитесь:proglang.su
Что такое HTML и с чего начать изучение HTML?

Не будем вдаваться в подробности и историю что такое HTML, а сразу перейдем основным моментам. HTML — это основа построения любого сайта! При изучении темы сайтостроения необходимо начинать именно с него. Здесь нет ничего тяжелого. Освоить данную технологию сможет АБСОЛЮТНО КАЖДЫЙ!
Сразу хочу заметить, что это НЕ язык программирования, а язык разметки.
Почему выучить HTML легко?
Чтобы говорить свободно на английском языке не нужно знать все слова, которые есть в английском языке. Так и здесь, Вам лишь необходимо усвоить некоторые из основных тегов и научиться с ними работать. А дальше Вам лишь останется практиковаться и нарабатывать навык.
Давайте приступим к изучению этой увлекательной, и одновременно простой, технологии.
Немного теории…
Любая страница состоит из тегов. То есть страница выглядит на самом деле не так как мы привыкли это видеть, а состоит из множества тегов, каждый из которых, играет определенную роль.
Это похоже на большую стену из кирпичиков. Если все кирпичики на ней положены аккуратно, то и вся стена выглядит красиво. Поэтому при написании структуры страницы необходимо уделять внимание каждому тегу, потому что он является "кирпичиком" для нашей будущей страницы.
Но что такое тег в HMTL?
Это элемент HTML страницы, который так или иначе влияет на отображение и разметку страницы. На словах понять это достаточно сложно, поэтому необходимо сразу все смотреть именно на практике и привыкать к коду. Посмотрите на изображение ниже:

Это структура самой простой страницы. А вот эти повторяющиеся слов в треугольных скобках — это и есть теги. Если Вы откроете свой текстовый редактор и напишете данный код, а затем сохраните в формате HTML, то у Вас получится HTML страничка. Пока что не понятно что такое HTML? 🙂
Из этой структуры можно увидеть те теги, которые должны обязательно присутствовать. Это теги:
Чтобы было более наглядно, я выделил их оранжевым цветом на изображении ниже:

Все, что мы будем писать между тегами <head> и </head> мы не увидим на нашей странице. Эти теги могут сообщать браузеру о кодировке, о заголовке нашей страницы, здесь могут подключить различные стили, скрипты и так далее. Все это Вы увидите в последующих уроках.
А вот все теги, которые мы будем писать между тегами <body> и </body>, в зависимости от его предназначения, будет влиять именно на структуру нашей HTML страницы.
Ну что, стало более понятно что такое HTML? 😉 Но мы не останавливаемся и движемся дальше…
Некоторые теги могут иметь закрывающий тег, а некоторые нет. Например тега <body> есть закрывающий тег </body>. Как Вы могли уже догадаться, закрываются теги с помощью наклонной черты.
Очень важно соблюдать открытие и закрытие тегов. Чтобы не было ошибок. Браузер ошибку может и не показать, а вот структура Вашей страниц будет неправильной и при дальнейшей работе со стилями (где займемся внешним видом) будут большие проблемы. Поэтому если у тега есть закрывающий тег, то он обязательно должен присутствовать в правильном месте.
Давайте на примере разберем как НЕ надо закрывать теги и в каком порядке это необходимо делать. Пример двух тегов:
Правильный HTML КОД
| 1 | <div><p>Произвольный текст</p></div> |
То, что Вы видите выше — это правильный порядок написания закрывающих тегов. Но может быть такая ситуация
ОШИБКА В HTML КОДЕ
| 1 | <div><p>Произвольный текст</div></p> |
Так закрывать теги категорически запрещается!
Практика, чтобы понять что такое HTML…
Поближе узнать, что такое HTML, можно лишь на практике. Для этого можно использовать любой текстовый редактор. Даже блокнот. Но я рекомендую использовать Notepad++, потому что функци для работы с HTML здесь гораздо больше. Скачать его можно по ссылке Скачать Notepad++. В данном редакторе есть все возможности для создания и редактирования HTML страниц.
Начнем. После открытия программы вы увидите такое окошко:

Чтобы создать HTML страницу, необходимо ввести "тело" страницы в данное окошко. Вы можете скопировать текст ниже и просто вставить его. Но лучше введите все руками. Так Вы сможете быстрее запомните и привыкнете к тегам.
HTML КОД
| 1 2 3 4 5 6 7 8 9 | <html> <head> <title>Изучаю HTML - Начало</title> </head> <body> <h2>Основной заголовок</h2> <h4>Более маленький подзаголовок</h4> </body> </html> |
Итак, у вас должно получиться следующее:

Далее необходимо сохранить данную страницу в HTML формате. Для этого нажимаем в меню "Файл", здесь жмем "Сохранить как…". Вводим имя HTML страницы. Я назвал ее index.html. Затем просто сохраняем в удобное место у себя на компьютере. После этого появится подсветка HTML тегов, потому что редактор Notepad++ поймет что это HTML документ. А с подстветкой работать гораздо приятнее.

Сейчас можно открыть этот файл в любом браузере. И если Вы в своем браузере увидели такую вот картину:

То необходимо дописать после закрывающего тега </title> вот такую строчку:
HTML КОД
И убедиться в том, что в текстовом редакторе выбрана кодировка UTF-8 (без BOM):

И тогда Вы увидите следующую страничку в своем браузере:

Видео урок — что такое HTML? (практика)
Если при прочтении Вам было тяжело, то посмотрите данный видео урок:
Вывод
Замечательно, у нас получилась первая HMTL страничка. Если же что-то пошло не так, то обязательно повторите все шаги и убедитесь в том, что Вы все сделали точно также. Теперь у Вас сложилось первое впечатление о HTML и что это такое.
Урок 1. Что такое HTML — изучаем что такое HTML структура 4.88/5 (97.50%) 16 голос(ов)
Понравилась статья - расскажи друзьям! :)
Вконтакте
Одноклассники
Google+
www.sitehere.ru
Основы html для начинающих на понятном языке
Основы html для начинающих, что сейчас должен знать каждый начинающий вебмастер или блогер. Если вы хотите научиться создавать элементарные сайты, понимать сам код, знать, что за чем стоит и должно идти, без знаний основ языка хтмл этого сделать просто невозможно. На своем блоге у меня будет целая цепочка статей, которые я посвящу этой теме от А до Я, опишу каждый тег, который присутствует в документе, что он обозначает и как его правильно использовать.
к оглавлению ↑
Основы хтмл
Если не знать самого элементарного, дальше вам путь закрыт. Я считаю, что каждый человек, который решил заниматься разработкой и созданием сайтов, должен знать и понимать основы, из чего состоит сам сайт, как он работает и что происходит в самом коде.
Языков программирования конечно не мало, все они по-своему сложные, но есть такие, которые нужно знать обязательно. Если вы хотите красиво оформить письмо для отправки по почте, у вас имеется своя группа Вконтакте, группа в других социальных сетях, тот же канал youtube, вам необходимо ковыряться в коде на любом из движков сайта, базовые понятия вы просто должны знать.
Навел только несколько примеров, на самом деле сейчас эти знания все чаще и чаще применяются в интернете. Я больше практик чем теоретик, поэтому в моих статьях в данной рубрике я буду показывать вам свои примеры, как и что я делал, step by step. Буду выкладывать как примеры страниц, так и целые сайты.
Html документ это самый простой текстовый документ, язык тегов, с которым вы сталкиваетесь каждый день на просторах интернета. Теги описывают структуру документа. Оформляются теги угловыми < >скобками, внутри которых пишется название тега. Браузер просматривает структуру документа, выстраивает ее и отображает уже по своим инструкциям на вашем мониторе, если вы конечно все сделали правильно.
Весь этот процесс начинается перед тем, как вы уже видите готовую картинку. Браузеры обрабатывают документ последовательно, от самого начала и до конца. Включая в себя полностью все, что должно быть на странице. Таблицы, картинки, скрипты и так далее, кроме это включая в себя стили CSS.
к оглавлению ↑
Основы для начинающих
Что такое html — если посмотреть, что пишет Википедия - (HyperText Markup Language) язык гипертекстовой разметки документов. Большинство страниц в интернете содержат разметку страницы на этом языке. Данный язык интерпретируется браузерами, полученный в результате форматированный текст отображается на вашем мониторе компьютера или мобильного устройства.
Данный язык по своей сути очень легкий и доступный в обучении. Выучить и понять его основы может каждый желающий человек. Для использования такого языка нужно знать и применять дескрипторы, которые еще называются тегами. Именно с помощью тегов и создается документ.
Из чего должна состоять структура документа, какие теги должны присутствовать. Давайте разберем все на одном маленьком примере. Я написал некоторый текст в MS Office и показал его вот на этом скриншоте.

Чтобы отобразить данный текст в браузере так же само, как он был написан в документе, для этого нужно к нему добавить разметку страницу, которая включает в себя некоторые теги. Для начала посмотрите на них, дальше я опишу каждый, кто за что отвечает.
<html> <body> <h3>Блог Евгения Несмелова ! Nesmelov.ru Основы html и css для начинающих</h3> <p>Добро пожаловать на мой блог, сейчас вы проходите урок по Основам HTML. Если вам понравилась данная статья, можете подписаться на данный блог, чтоб получать новые статьи на свой электронный ящик.</p> <h3>Блог Евгения Несмелова ! Nesmelov.ru Основы html и css для начинающих</h3> <p>Из каких тегов состоит любой html документ, что в него входит и где все это нужно прописать.</p> </body> </html>
<html> <body> <h3>Блог Евгения Несмелова ! Nesmelov.ru Основы html и css для начинающих</h3> <p>Добро пожаловать на мой блог, сейчас вы проходите урок по Основам HTML. Если вам понравилась данная статья, можете подписаться на данный блог, чтоб получать новые статьи на свой электронный ящик.</p> <h3>Блог Евгения Несмелова ! Nesmelov.ru Основы html и css для начинающих</h3> <p>Из каких тегов состоит любой html документ, что в него входит и где все это нужно прописать.</p> </body> </html> |
Любой код состоит из символов, которые помещаются в угловые скобки. Все это называется элементами. Все элементы, как правило состоят из двух тегов, открывающего и закрывающего. Советую вам изначально внимательно смотреть за тегами, если вы пропустите один из них и не закроете его, вам нужно будет пересматривать большие части кода, чтоб найти ошибку.
Были случаи, когда на это уходил не один день, человек обращается и просит ему помочь, он не может найти у себя ошибку на сайте, поэтому всегда смотрите очень внимательно, что и где вы пишите. Давайте теперь на данном примере посмотрим на каждый элемент из кода, что в нем написано, что это означает и что получается в итоге.
Большинство тегов парные, которые включают в себя открывающийся тег и закрывающийся. Кроме таких тегов, существуют еще и одиночные теги. Теги могут идти вместе с другими, таким образом вкладываются друг в друга. Например отобразить текст сразу жирным и курсивом.
<strong><i>Текст</strong></i>
<strong><i>Текст</strong></i> |
к оглавлению ↑
Структура html документа
Напомню еще раз раз, нужно следовать правилам, которые присутствуют в документе. Именно так браузер понимает что находится на странице, ее последовательность, содержание и так далее.
Тег — это компонент, который говорит веб браузеру выполнить ту или иную задачу. Например присутствие абзаца, таблицы, формы или изображения.
Атрибут — изменяет тег. Например можно абзац выровнять по центру или по правому краю, задать так же расположение изображения на странице и так далее.
ВСЕГДА закрывайте теги, если вы его отрыли, обязательно нужно его закрыть. В противном случае будет ошибка и ваш документ будет некорректно отображаться на странице. Так же существуют исключения, про них не следует забывать.
Четко нужно понимать, что существует заголовок документа и его тело. Заголовок это все, что состоит в теге <head>. Тело документа (<body>), в теле документа состоит все содержимое страницы. Если возникает необходимость оставить участок кода для себя, тем самым заключить данные теги в комментарии, для этого используется тег <!>. Все, что находится внутри такого тега, служит в роли комментария и не воспринимается браузерами.
к оглавлению ↑
<html>
Начнем с самого первого. В начале документа я открыл тег <html> и в конце я его закрыл </html>. Данный код присутствует абсолютно в каждом документе, он говорит браузеру, что все, помещенное между этими тегами, является HTML кодом. Является корнем самого документа, все, что в дальнейшем присутствует за этим тегом, уже не включается в документ и не воспринимается браузерами. В самом начале документа тег открывается и в самом конце он обязательно должен быть закрытым.
к оглавлению ↑
<head>
Весь раздел этого тега содержит в себе всю техническую информацию документа. Как и предыдущий тег, head так же должен быть открыт и в конце закрыт. В такую информацию относится заголовок страницы, ее описание, ключевые слова для поисковых систем и кодировку. Про кодировку немного ниже.
<head> Содержание </head>
<head> Содержание </head> |
к оглавлению ↑
<Title>
Данный тег включается в head, он должен быть написан внутри тега head. Данный тег title является обязательным и должен присутствовать в каждом html документе. В добавок к этому он отображается как заголовок окна браузера. Длинна такого заголовка не должна превышать 60 символов. В тексте такого заголовка должна содержаться максимально полная информация, которая характеризует содержание страницы.
Если вы написали в заголовке "Привет Мир", именно эта информация должна отображаться на странице и никакой другой. Не стоит обманывать людей и поисковые машины, они этого не любят, тем самым вы делаете хуже себе. Информация, которая содержится в этом теге, должна соответствовать содержанию вашей страницы.
к оглавлению ↑
<meta>
После обязательного тега title, идет необязательный, но так же не мало важный тег meta. Данный тег является одинарным. С помощью данного тега задается описание для страницы (description) и ее ключевые слова (keywords).
<meta name="keywords" content="Ключевые слова задаются через запятую"> <meta name="description" content="Описание страницы не больше двух предложений">
<meta name="keywords" content="Ключевые слова задаются через запятую"> <meta name="description" content="Описание страницы не больше двух предложений"> |
Кроме этого, в теге meta могут содержаться данные про автора страницы и другие свойства метаданных. Можно запретить индексацию страницы в целом для поисковых машин. Поставить автоматическое обновление страницы через 20 секунд или через 5 секунд с последующим переходом на другую страницу.
<meta name="robots" content="index, follow"> <meta http-equiv="refresh" content="20"> <meta http-equiv="refresh" content="5; url=http://nesmelov.ru/">
<meta name="robots" content="index, follow"> <meta http-equiv="refresh" content="20"> <meta http-equiv="refresh" content="5; url=http://nesmelov.ru/"> |
Таких элементов meta может быть несколько, так как они могут нести абсолютно разную информацию. Остальные пользователи, когда открывают страницу в браузере, не видят все ваши описания, все это остается скрытым от глаз.
к оглавлению ↑
<style>
Тег style так же можно использовать для задания стилей на странице. Если вы используете много разных стилей css, в таком случае желательно задавать их в отдельном файле. Если нужно указать несколько из них, все это можно задать прямо в html документе.
<style type="text/css"> .base { width: 100px; background-color: #000; height: 150px; color: #fff; }
<style type="text/css"> .base { width: 100px; background-color: #000; height: 150px; color: #fff; } |
Или добавить стили конкретно к одному тегу, для этого внутри самого тега нужно добавить элемент style. Данный тег нужно использовать внутри контейнера <head>, который задает стили для страницы. Можно использовать несколько таких тегов, ошибкой это не будет.
<h4>
<h4> |
к оглавлению ↑
<link>
Немного похожий с предыдущим тегом, с помощью тега link можно задать стили для документа, которые находятся в другом файле. Другими словами, можно подключить к существующему документу полную таблицу стилей css, которая состоит из множества свойств. Тем самым вы уменьшаете размер документа, который в итоге будет быстрее грузиться и открываться на компьютере или мобильном устройстве при слабой скорости интернета.
Подключать можно больше одного файла, тут ограничений нет. Закрывать такой тег не нужно. Если все сделать правильно, к вашему документу будут подгружаться конкретные стили из отдельного файла. Данный тег можно добавить в основы html и не забывать про его существование. В итоге получается такая картинка:
<link href="css/style-lg.css" rel="stylesheet"> <link href="css/style-md.css" rel="stylesheet"> <link href="css/style-sm.css" rel="stylesheet">
<link href="css/style-lg.css" rel="stylesheet"> <link href="css/style-md.css" rel="stylesheet"> <link href="css/style-sm.css" rel="stylesheet"> |
к оглавлению ↑
<script>
С помощью тега script к документу можно подключить разные сценарии (скрипты). Присутствие закрывающего тега обязательно. Сам скрипт может располагаться в начале документа, внутри и в конце.
<script type="text/javascript" href="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<script type="text/javascript" href="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> |
к оглавлению ↑
<body>
Говорит браузеру, что все помещенное между этими тегами, должно отобразиться в окне вашего браузера. Вот основные теги, которые могут присутствовать абсолютно в каждом документе. Тег body служит в качестве основного тела страницы, который включает в себя все ее содержимое. Данный тег желательно открывать и в конце документа не забыть закрывать.
к оглавлению ↑
Заголовки страницы h2 h3 h4
Поехали дальше, мы видим тег <h2>, который так же открывается и закрывается. Данный тег обозначает основной заголовок текста, в большинстве случаев под заголовком h2 идет название страницы. На самом деле данных заголовком всего шесть. <h2> <h3> <h4> <h5> <h5> <h6>. Их так же используют в SEO, но это уже немного другая тема. Я обязательно выделю для этого одну статью и дам подробное описание для них, подписывайтесь на обновления блога, чтоб ничего не пропустить.
Наличие таких заголовком в статье сыграет важную роль при продвижении страницы. Кроме этого, ихнее использование дает вам четкую структуру страницы, ее заголовок, подзаголовки, выделения, подпункты и так далее. Всегда пользуйтесь ними и применяйте на практике. На многих CMS, например таких как WordPress, при написании текста, можно заметить «заголовок 1», "заголовок 2", "заголовок 3" и так далее. Именно они и отвечают за h2, h3 и h4.
к оглавлению ↑
<p>
Если вы пишите основной текст с нового абзаца, вы пишите тег <p> в начале и закрываете его в конце </p>. Обозначение абзаца в html равносильно создание нового абзаца в документе MS Word. Больше ничего нового в документ я не добавлял. Но, это еще далеко не все, что должно присутствовать в html документе. Посмотрим на еще один пример, описание будет немного позже.
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>HTML документ</title> </head> <body> <p> <b> Этот текст будет полужирным, <i>а этот - ещё и курсивным</i> </b> </p> </body> </html>
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>HTML документ</title> </head> <body> <p> <b> Этот текст будет полужирным, <i>а этот - ещё и курсивным</i> </b> </p> </body> </html> |
к оглавлению ↑
Основные элементы Head и Title

В каждом документе присутствует элемент head и Title. Первый из них <head>, который идет сразу после первого тега <html>. В данном теге идет вся информация о странице, в нем так же заключается элемент <title>. Title –информация о заголовке странице, другими словами название страницы, ее имя. Именно в тайтл вы указываете правильное название страницы, по которому пользователь будет искать вас через поисковую систему, очень важный момент. Оба элемента должны быть открыты и так же закрыты. Закрывается каждый элемент знаком «/». В итоге получается вот такая картинка.
<html> <head> <title>Заголовок&</title> </head> <body>\Содержание страницы</body> </head> </html>
<html> <head> <title>Заголовок&</title> </head> <body>\Содержание страницы</body> </head> </html> |
Как видите, ничего сложного нет. Перед вами самые основные теги, которые должны присутствовать в каждом html документа. Не забывайте закрывать каждый из них, иначе браузер не сможет воспринять полноценную картину кода. Это нужно знать и помнить всегда. Дальше вы уже начинаете вставлять текст, картинки, видео и так далее. Но это уже будет в других статьях.
к оглавлению ↑
Редактор Notepad++

Для работы с кодом используйте программку Notepad++. Она бесплатная, найти ее в интернете не составит труда. Очень удобная для восприятия любого кода, так же удобно показывается открывающийся тег и закрывающийся. Поддерживаем синтаксис более 40 языков программирования. Как раз то, что нужно для изучения основ html.
Notepad превышает во всех смыслах обычный блокнот. Для максимального удобства, простоты и учебы данный редактор изначально необходимо установить на компьютер. Самое основное преимущество и удобство, редактор Notepad++ показывает подсказки при написании кода, что делает вашу работу быстрее и качественней в разы.
к оглавлению ↑
Элемент DOCTYPE
В каждом документе так же должен быть указан вот такой элемента doctype. Для чего он нужен и что в нем должно быть. Обычно народ сильно не увлекается этими строчками, копируют себе в документы и работают спокойно. Данные элементы говорят браузеру, какая версия html используется в документе, какое описание страницы, какая используется кодировка, какие ключевые слова включены, кто автор и как называется страница.
Ставятся они обычно в самом начале. Существует несколько вариантов и все они отличаются друг от друга, я напишу один пример, который используется чаще всего. Данную заготовку можно использовать как готовый шаблон. Далее будет понятное описание каждой строчки, проблем с этим быть не должно.
<!DOCTYPE html "-//w3c//dtd XHTML 1.0 Transitional//EN" "http://www.w3c.org/TR/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html;charset=windows-1251" /> <meta name="Nesmelov.ru" content="Nesmelov Evgeniy" /> <meta name="description" content="полное описание данной страницы, о чем идет речь. 1-2 предложения" /> <meta name="keywords" content="джинсы, купить джинсы, зауженные джинсы, крутые джинсы, мужские крутые джинсы" /> <title>Заголовок данной страницы</title> </head> <body> </body> </html>
<!DOCTYPE html "-//w3c//dtd XHTML 1.0 Transitional//EN" "http://www.w3c.org/TR/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html;charset=windows-1251" /> <meta name="Nesmelov.ru" content="Nesmelov Evgeniy" /> <meta name="description" content="полное описание данной страницы, о чем идет речь. 1-2 предложения" /> <meta name="keywords" content="джинсы, купить джинсы, зауженные джинсы, крутые джинсы, мужские крутые джинсы" /> <title>Заголовок данной страницы</title> </head> <body> </body> </html> |
к оглавлению ↑
Информация для чайников
Коротко на понятном языке про основы html: Данная строчка говорит браузеру о том, что данный документ является XHTML версия 1.0, используется английский язык и вся эта каша расположена по данному адресу. Далее в теге meta указываем кодировку, которая используется. Чаще всего используется виндовс 1251.
Далее часто различные конторы по созданию шаблонов, скриптов и так далее...указывают свое название организации или просто имя фамилию и отчество. Не обязательный meta тег, но встретить его можно часто.
Description — затрагивается тема по SEO, один из трех главных тегов, который должен присутствовать абсолютно в каждом документе, данный тег указывает описание страницы. Что написано на этой странице, короткое описание, не больше двух предложений. Тег keywords, так же затрагивается тема по SEO, данный тег является обязательным. В нем пишутся ключевые слова, по которым пользователи интернета будут находить вас через поисковые системы.
В теге title идет название самого документа, его заголовок, который мы видим в браузере. Наверное самый важный тег во всем документе, который больше всего влияет на продвижение страницы. В статье по добавлению и оформлению текста html идет описание данного тега более детально.
Что необходимо запомнить с данного урока про основы html:
- Почти все теги открываются и закрываются;
- Начинается документ с тега <html>;
- Наличие тега <head>;
- Наличие тега <body>;
- Четкая структура html документа.
Все главные страницы всегда должны называться словом index. Так принято и так все привыкли, без разницы какое будет расширение у файла, это может быть и html и php. Называется он всегда только так.
Посмотрите видео про основы html от компании Webformyself.
Язык гипертекстовой разметки, базовые элементы и структура. Все это и многое другое я постараюсь описать на своем блоге. В первую очередь для новичков будет написана полезная информация, предоставлен пример кода и возможность скачать сам пример вместе с готовой страницей.
Евгений Несмелов
nesmelov.ru
Элементы HTML - это... Что такое Элементы HTML?
Эта статья посвящена в основном элементам HTML. Чтобы узнать о формате элементов Википедии, см. Википедия:Как редактировать статью и m:Помощь:HTML в викитексте
Элемент HTML — это основная структурная единица веб-страницы, написанная на языке HTML
Структура HTML-документа
HTML — это теговый язык разметки документов, то есть любой документ на языке HTML представляет собой набор элементов, причем начало и конец каждого элемента обозначается специальными пометками, называемыми тегами. Регистр, в котором набрано имя тега, в HTML значения не имеет. Элементы могут быть пустыми, то есть не содержащими никакого текста и других данных (например, тег перевода строки <br>). В этом случае обычно не указывается закрывающий тег. Кроме того, элементы могут иметь атрибуты, определяющие какие-либо их свойства (например, размер шрифта для тега <font>). Атрибуты указываются в открывающем теге. Вот пример части разметки HTML-документа:
<p>Текст между двумя тегами - открывающим и закрывающим.</p> <a href="http://www.example.com">Здесь элемент содержит атрибут href.</a> А вот пример пустого элемента: <br>Каждый HTML-документ, отвечающий спецификации HTML какой-либо версии, обязан начинаться со строки декларации версии HTML <!DOCTYPE>, которая обычно выглядит примерно так:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">Если эта строка не указана, то добиться корректного отображения документа в браузере становится труднее.
Далее обозначается начало и конец документа тегами <html> и </html> соответственно. Внутри этих тегов должны находиться теги заголовка (<head></head>) и тела (<body></body>) документа.
Варианты DOCTYPE для HTML 4.01
- Строгий (Strict): не содержит тегов, помеченных как «устаревшие» или «не одобряемые» (deprecated).
- Переходный (Transitional): содержит устаревшие теги в целях совместимости и упрощения перехода со старых версий HTML.
- С фреймами (Frameset): аналогичен переходному, но содержит также теги для создания наборов фреймов.
DOCTYPE для HTML 5
В отличие от предыдущих версий тег всего один [1]
Основные элементы («теги»)
Теги и их параметры нечувствительны к регистру. То есть <A HREF="http://yahoo.com"> и <a href="http://yahoo.com"> означают одно и то же.
В последних версиях HTML практически у каждого тега огромное число необязательных параметров — обычно не меньше 15. Мы приводим только основные параметры тегов.
Гиперссылки
<A HREF="filename" target="_self">название ссылки</A>- Атрибут HREF задает значение адреса документа, на который указывает ссылка.
- filename — имя файла или адрес Internet, на который необходимо сослаться.
- название ссылки — название гипертекстовой ссылки, которое будет отображаться в браузере, то есть показываться тем, кто зашел на страницу.
- TARGET — задает значение окна или фрейма, в котором будет открыт документ, на который указывает ссылка. Возможные значения атрибута:
- _top — открытие документа в текущем окне;
- _blank — открытие документа в новом окне;
- _self — открытие документа в текущем фрейме;
- _parent — открытие документа в родительском фрейме.
Значение по умолчанию: _self.
Текстовые блоки
- <h2> … </h2>, <h3> … </h3>, … ,<H6> … </H6> — заголовки 1, 2, … 6 уровня. Используются для выделения частей текста (заголовок 1 — самый большой, 6 — почти равен обычном тексту по умолчанию).
- <P> — новый абзац. Можно в конце абзаца поставить </P>, но это не обязательно.
- <BR> — новая строка. Этот тег не закрывается (то есть не существует тега </BR>)
- <HR> — горизонтальная линия
- <BLOCKQUOTE> … </BLOCKQUOTE> — цитата. Обычно текст сдвигается вправо.
- <PRE> … </PRE> — режим preview. В этом режиме текст заключается в рамку и никак не форматируется (то есть теги, кроме </PRE>, игнорируются, и переводы строки ставятся там, и только там, где они есть в оригинальном документе).
- <DIV> … </DIV> — блок (обычно используется для применения стилей CSS)
- <SPAN> … </SPAN> — строка (обычно используется для применения стилей CSS)
Форматирование текста
- <EM> … </EM> — логическое ударение (обычно отображается курсивным шрифтом)
- <STRONG> … </STRONG> — усиленное логическое ударение (обычно отображается жирным шрифтом)
- <I> … </I> — выделение текста курсивом
- <B> … </B> — выделение текста жирным шрифтом
- <U> … </U> — подчёркивание текста
- <S> … </S> (или <STRIKE> … </STRIKE> )— зачёркивание текста
- <BIG> … </BIG> — увеличение шрифта
- <SMALL> … </SMALL> — уменьшение шрифта
- <BLINK> … </BLINK> — мигающий текст. Внимание! Этот тег не работает в браузере Internet Explorer версий 5 и ниже без применения JavaScript
- <MARQUEE> … </MARQUEE> — сдвигающийся по экрану текст.
- <SUB> … </SUB> — подстрочный текст. Например, H<SUB>2</SUB>O создаст текст h3O.
- <SUP> … </SUP> — надстрочный текст. Например, E=mc<SUP>2</SUP> создаст текст E=mc2.
- <FONT параметры> … </FONT> — задание параметров шрифта. У этого тега есть следующие параметры:
- COLOR=color — задание цвета. Цвет может быть задан в шестнадцатеричной форме как #rrggbb (первые 2 шестнадцатеричные цифры задают красную компоненту, следующие 2 — зелёную, последние 2 — синюю) или названием.
- FACE=шрифт задание гарнитуры шрифта
- SIZE=размер задание размера шрифта. Размер от 1 до 7: стандартный по умолчанию 3. Есть много способов изменить стандартный размер.
- SIZE=+изменение или SIZE=-изменение — изменение размера шрифта от стандартного. Например, +2 означает размер на 2 больше стандартного.
Так, например,
Сигналом к началу атаки являются <U>три</U> <FONT SIZE="+2">больших</FONT> <FONT COLOR="green">зелёных</FONT> свистка.создаст текст
Сигналом к началу атаки являются три больших зелёных свистка.Списки
<UL> <LI> первый элемент </LI> <LI> второй элемент </LI> <LI> третий элемент </LI> </UL>создаёт список
- первый элемент
- второй элемент
- третий элемент
Если вместо <UL> (Unordered List — ненумерованный список) поставить <OL> (Ordered List — нумерованный список), список получится нумерованным:
- первый элемент
- второй элемент
- третий элемент
У этих тегов есть параметры:
type = "тип"где тип — форма: в <UL> — символов
- square — квадрат
- round — окружность
- disk — круг: по умолчанию
а в <OL> — цифр или букв
- A или а (латинскими буквами) — буквенный список: соответственно заглавными или строчными буквами
- I или i — римские цифры: соответственно заглавными или строчными буквами
- 1 — арабские цифры: по умолчанию
пишется так:
<ol type="i"> <li> Первое </li> <li> Второе </li> <li> И т.д. </li> </ol>и создаст следующее:
- Первое
- Второе
- И т.д.
Параметр start = "начало" (только для <OL> ), определяющий начало нового отсчёта: например, если нужно не 1, 2, 3, а 24, 25, 26
Пишется так:
<ol start="24"> <li> Двадцать четыре </li> <li> Двадцать пять </li> <li> И т.д. </li>и создаст следующее:
- Двадцать четыре
- Двадцать пять
- И т.д.
и, наконец для тега <LI> параметр value = "следующий" — если необходимо перескочить с одной цифры на другую: например, не 1, 2, 3, 4, а 1, 2, 22, 23
<ol> <li> Один </li> <li> Два </li> <li value="22"> Двадцать два </li> <li> Двадцать три </li>создаст следующее:
- Один
- Два
- Двадцать два
- Двадцать три
Наконец, третьим, и последним, списком является список определений:
<DL> <DT> Кошка </DT> <DD> мяукающее домашнее животное </DD> <DT> Кот </DT> <DD> муж кошки </DD> <DT> Крокодил </DT> <DD> большой африканский зверь с острыми зубами </DD> </DL>создаст следующее:
Кошка мяукающее домашнее животное Кот муж кошки Крокодил большой африканский зверь с острыми зубамиМежду прочим, теги <LI>, <DT>, <DD> можно и не закрывать.
Объекты
- EMBED — вставка различных объектов: не-HTML документов и media-файлов
- APPLET — вставка Java-апплетов
- SCRIPT — вставка скриптов.
Изображения
- IMG — вставка изображения. Этот тег не закрывается.
- SRC — имя или URL
- ALT — альтернативное имя (отобразится, если в браузере запретить отображать картинки)
- TITLE — краткое описание изображения (отобразится при наведении курсора на картинку)
- WIDTH, HEIGHT — размеры (если не совпадают с истинными размерами картинки, то изображение «растянется»/«сожмется»)
- ALIGN — задает параметры обтекания текстом (top, middle, bottom, left, right)
- VSPACE, HSPACE — задают размеры вертикального и горизонтального пространства вокруг изображения
Пример:
<IMG SRC=url ALT="текст" TITLE="текст">Изображение можно сделать ссылкой:
<A HREF=url ><IMG SRC=url></A>Таблицы
- TABLE — создание таблицы. Параметры тега:
- BORDER — толщина разделительных линий в таблице
- CELLSPACING — расстояние между клетками
- CAPTION — заголовок таблицы (этот тег необязателен)
- TR — строка таблицы
- TH — заголовок столбца таблицы (этот тег необязателен)
- TD — ячейка таблицы
- height — высота таблицы
- width — ширина таблицы
Так, например,
<TABLE BORDER="1" CELLSPACING="0"> <CAPTION> Улов крокодилов в Мумбе-Юмбе </CAPTION> <TH> Год </TH> <TH> Улов </TH> <TR> <TD> 1997 </TD> <TD> 214 </TD> </TR> <TR> <TD> 1998 </TD> <TD> 216 </TD> </TR> <TR> <TD> 1999 </TD> <TD> 207 </TD> </TR> </TABLE>Создаст таблицу:
| 1997 | 214 |
| 1998 | 216 |
| 1999 | 207 |
У тега TABLE есть ещё параметр CELLPADDING. Он определяет расстояние в пикселях между рамкой ячейки и её содержимым. Например, если заменить первую строку таблицы на
<TABLE BORDER="1" CELLSPACING="0" CELLPADDING="5">таблица получится такой:
| 1997 | 214 |
| 1998 | 216 |
| 1999 | 207 |
Другой параметр тегов TABLE, TR, TH, TD — ALIGN. Он определяет выравнивание. Возможные значения — center (по центру), left (по левому краю), right (по правому краю).
Параметр ALIGN в TD или TH определяет выравнивание для содержимого внутри данной ячейки, в TR — для содержимого всех ячеек строки, TABLE — для самой таблицы на страничке. Для каждой ячейки берётся выравнивание из TD или TH, если оно не задано — из TR, если и оно не задано — по центру для TH или по левому краю для TD.
Например, если заменить первые строки таблицы на
<TABLE BORDER="1" CELLSPACING="0" ALIGN="center"> <CAPTION> Улов крокодилов в Мумбе-Юмбе </CAPTION> <TH> Год </TH> <TH> Улов </TH> <TR> <TD> 1997 </TD> <TD ALIGN="CENTER"> 214 </TD>таблица получится такой:
| 1997 | 214 |
| 1998 | 216 |
| 1999 | 207 |
Незакрытые теги TD, TR и TH приводят к некорректному отображению, особенно при работе с вложенными таблицами.
Формы
Создание форм в HTML является довольно сложным делом. Здесь приводятся только названия основных тегов.
- FORM — создание формы
- INPUT — элемент ввода (может иметь разные функции — от ввода текста до отправки формы)
- TEXTAREA — текстовая область (многострочное поле для ввода текста)
- SELECT — список (обычно в виде выпадающего меню)
- OPTION — пункт списка
Символы
Чтобы создать символ, необязательно искать его на клавиатуре. Можно просто набрать тег (например, чтобы получить ¢, надо набрать следующее: ¢). Пробел - , ударение - ́ и т. д.
Названия цветов
В HTML определены следующие цвета.
| black | #000000 |
| silver | #c0c0c0 |
| maroon | #800000 |
| red | #ff0000 |
| navy | #000080 |
| blue | #0000ff |
| purple | #800080 |
| fuchsia | #ff00ff |
| green | #008000 |
| lime | #00ff00 |
| olive | #808000 |
| yellow | #ffff00 |
| teal | #008080 |
| aqua | #00ffff |
| gray | #808080 |
| white | #ffffff |
Основные символы
| < | < | |
| > | > | |
| & | & | |
| | неразрывный пробел (на этом пробеле не переводится строка) | |
| § | § | |
| № | № | |
| © | © | копирайт (copyright) |
| ® | ® | зарегистрированный товарный знак (registered trademark) |
| ™ | ™ | товарный знак (trademark) |
| ° | ° | градусы |
| « | « | открывающая кавычка в русском языке |
| » | » | закрывающая кавычка в русском языке |
| … | … | многоточие |
| — | — | тире |
| • | • | жирная точка |
| ± | ± | плюс-минус |
| − | − | минус |
Клавиатурные символы ' и " в русском языке кавычками не являются. Также неправильно на сайтах заменять №, ©, ®, ™, °C на N, (c), (R), TM, C.
Дефис, тире и минус — три разных знака.
- Клавиатурный символ - называется дефис и используется внутри слов.
- Минус шире дефиса. Он используется для записи отрицательных чисел и операции вычитания.
- Тире ещё шире, чем минус. Оно используется между словами и отбивается пробелами. Для обозначения числовых интервалов тоже используется тире, но пробелами не отбивается.
В электронной переписке, чатах и форумах все эти упрощения допустимы: можно заменять тире и минусы дефисами, знак номера на N, кавычки теми, что есть на клавиатуре и т. д.
Символы <, > и & нельзя отобразить в HTML обычным образом, потому что они имеют специальный смысл.
Большинство спецсимволов см. на сайте about.com.
dic.academic.ru
теги - полный список, таблица тегов по разделам
HTML-теги — основа языка HTML. Теги используются для разграничения начала и конца элементов в разметке.
Каждый HTML-документ состоит из дерева HTML-элементов и текста. Каждый HTML-элемент обозначается начальным (открывающим) и конечным (закрывающим) тегом. Открывающий и закрывающий теги содержат имя тега.
В таблице приведен полный список элементов, поддерживаемых HTML4 и HTML5. Экспериментальные и устаревшие теги исключены. Элементы, добавленные в спецификацию HTML5, выделены бирюзовым цветом.
Таблица 1. HTML-элементыДля удобства пользования я сгруппировала теги по тематическим разделам, добавив значения свойства display для каждого тега. Чтобы перейти к таблице, кликните по рисунку.
html5book.ru

















